jest-matcher-deep-close-to icon indicating copy to clipboard operation
jest-matcher-deep-close-to copied to clipboard

Support setup via jest.config.js

Open logi opened this issue 4 years ago • 3 comments
trafficstars

To avoid having to add this boilerplate to each test file that uses the library:

import {toBeDeepCloseTo,toMatchCloseTo} from 'jest-matcher-deep-close-to';
expect.extend({toBeDeepCloseTo, toMatchCloseTo});

the expect.extend line could instead be added at the bottom of index.js in which case the expectations can be made globally available in a user's jest.config.js with something like:

module.exports = {
    setupFilesAfterEnv: [
        'jest-extended',  // https://github.com/jest-community/jest-extended
        'jest-matcher-deep-close-to',  // https://github.com/maasencioh/jest-matcher-deep-close-to
        './jest-extensions',  // Our own extensions
    ],
}

I'd make a PR for this but I'm not set up for hacking on typescript code and this itch isn't annoying enough.

logi avatar Nov 27 '20 10:11 logi

bump on this

jakeleventhal avatar Sep 16 '21 12:09 jakeleventhal

Bump

smith558 avatar Aug 04 '22 16:08 smith558

I got something working based on https://github.com/jest-community/jest-extended/blob/2bd088758d08a5ada82f28d26757f1d7f4ccaca4/src/all/index.js. Getting it to play nicely with my other VS Code extensions, XO, etc. was a bit of a pain.

Here's where I'm using it in a project: https://github.com/Antyos/image-layout/tree/adf3b4acde4482390d2e006db802a2c9eb7e965c.

// ./jest.config.ts
module.exports = {
    setupFilesAfterEnv: [
        'jest.config.ts', 
        // ...
    ],
}
// ./jest.setup.ts
import { toMatchCloseTo, toBeDeepCloseTo } from 'jest-matcher-deep-close-to';

// Patch `toMatchCloseTo` and `toBeDeepCloseTo` into jest's expect()
interface MaybeHasJestExpect {
    expect?: jest.Expect;
}

// Based on: https://github.com/jest-community/jest-extended/blob/2bd088758d08a5ada82f28d26757f1d7f4ccaca4/src/all/index.js
const jestExpect = (global as unknown as MaybeHasJestExpect).expect;

if (jestExpect === undefined) {
    throw new Error(
        "Unable to find Jest's global expect. " +
            'Please check you have added jest-extended correctly to your jest configuration. ' +
            'See https://github.com/jest-community/jest-extended#setup for help.',
    );
}

jestExpect.extend({ toMatchCloseTo, toBeDeepCloseTo });
// ./src/global.d.ts
export * from 'jest-matcher-deep-close-to';

In my tsconfig.json, I had to comment out the "exclude" key to avoid getting: Property 'toBeDeepCloseTo' does not exist on type 'JestMatchers<Position[]>'. ts(2339) in jest.setup.ts.

{
  // ...

  // Comment out the following line
  "exclude": ["src/**/*.test.*"],
}

Antyos avatar Sep 05 '22 20:09 Antyos