Loose match one value in jest.toHaveBeenCalledWith

This can be done with asymmetric matchers (introduced in Jest 18) expect(track).toHaveBeenCalledWith( expect.objectContaining({ “action”: “PublicationPage”, “category”: “PublicationPage”, “label”: “7”, “name”: “n/a” }) ) If you use jest-extended you can do something like expect(track).toHaveBeenCalledWith( expect.objectContaining({ “action”: “PublicationPage”, “category”: “PublicationPage”, “label”: “7”, “name”: “n/a”, “intervalInMilliseconds”: expect.toBeWithin(999, 1002) }) )

Jest gives an error: “SyntaxError: Unexpected token export”

This means, that a file is not transformed through TypeScript compiler, e.g. because it is a JS file with TS syntax, or it is published to npm as uncompiled source files. Here’s what you can do. Adjust your transformIgnorePatterns allowed list: { “jest”: { “transformIgnorePatterns”: [ “node_modules/(?!@ngrx|(?!deck.gl)|ng-dynamic)” ] } } By default Jest doesn’t transform … Read more

How do I run a single test using Jest?

From the command line, use the –testNamePattern or -t flag: jest -t ‘fix-order-test’ This will only run tests that match the test name pattern you provide. It’s in the Jest documentation. Another way is to run tests in watch mode, jest –watch, and then press P to filter the tests by typing the test file … Read more

Mocking `document` in jest

Similar to what others have said, but instead of trying to mock the DOM yourself, just use JSDOM: // __mocks__/client.js import { JSDOM } from “jsdom” const dom = new JSDOM() global.document = dom.window.document global.window = dom.window Then in your jest config: “setupFiles”: [ “./__mocks__/client.js” ],

How do I deal with localStorage in jest tests?

Great solution from @chiedo However, we use ES2015 syntax and I felt it was a little cleaner to write it this way. class LocalStorageMock { constructor() { this.store = {}; } clear() { this.store = {}; } getItem(key) { return this.store[key] || null; } setItem(key, value) { this.store[key] = String(value); } removeItem(key) { delete this.store[key]; … Read more