22,936 questions
924
votes
28
answers
953k
views
How do I run a single test using Jest?
I have a test 'works with nested children' within the file fix-order-test.js.
Running the below runs all the tests in the file.
jest fix-order-test
How do I run only a single test? The below does ...
908
votes
34
answers
1.3m
views
How do I test a single file using Jest?
I am able to test multiple files using Jest, but I cannot figure out how to test a single file.
I have:
Run npm install jest-cli --save-dev
Updated package.json: `{ ... "scripts": { "...
751
votes
8
answers
274k
views
What is the difference between 'it' and 'test' in Jest?
I have two tests in my test group. One of the tests use it and the other one uses test. Both of them seem to be working very similarly. What is the difference between them?
describe('updateAll', () =&...
592
votes
23
answers
821k
views
How to test the type of a thrown exception in Jest
I'm working with some code where I need to test the type of an exception thrown by a function (is it TypeError, ReferenceError, etc.?).
My current testing framework is AVA and I can test it as a ...
506
votes
29
answers
548k
views
Message "Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout"
I'm using Puppeteer and Jest to run some front end tests.
My tests look as follows:
describe("Profile Tab Exists and Clickable: /settings/user", () => {
test(`Assert that you can ...
503
votes
11
answers
520k
views
How can I mock an ES6 module import using Jest?
I want to test that one of my ES6 modules calls another ES6 module in a particular way. With Jasmine this is super easy --
The application code:
// myModule.js
import dependency from './dependency';
...
491
votes
10
answers
202k
views
Can you write async tests that expect toThrow?
I'm writing an async test that expects the async function to throw like this:
it("expects to have failed", async () => {
let getBadResults = async () => {
await failingAsyncTest()
}
...
488
votes
14
answers
434k
views
How do you test for the non-existence of an element using jest and react-testing-library?
I have a component library that I'm writing unit tests for using Jest and react-testing-library. Based on certain props or events I want to verify that certain elements aren't being rendered.
...
434
votes
33
answers
494k
views
How to resolve "Cannot use import statement outside a module" from Jest when running tests?
I have a React application (not using Create React App) built using TypeScript, Jest, Webpack, and Babel. When trying to run yarn jest, I get the following error:
I have tried removing all packages ...
386
votes
32
answers
399k
views
How do I set a mock date in Jest?
I'm using moment.js to do most of my date logic in a helper file for my React components but I haven't been able to figure out how to mock a date in Jest a la sinon.useFakeTimers().
The Jest docs only ...
380
votes
24
answers
487k
views
Console.log statements output nothing at all in Jest
console.log statements output nothing at all in Jest. This was working for me yesterday, and all of sudden, it's not working today. I have made zero changes to my config and haven't installed any ...
379
votes
14
answers
213k
views
How to use ESLint with Jest
I'm attempting to use the ESLint linter with the Jest testing framework.
Jest tests run with some globals like jest, which I'll need to tell the linter about; but the tricky thing is the directory ...
347
votes
17
answers
451k
views
Test process.env with Jest
I have an application that depends on environmental variables like:
const APP_PORT = process.env.APP_PORT || 8080;
And I would like to test that for example:
APP_PORT can be set by a Node.js ...
346
votes
11
answers
661k
views
How to get the code coverage report using Jest?
Is there a way to have code coverage in the JavaScript Jest testing framework, which is built on top of Jasmine?
The internal framework does not print out the code coverage it gets. I've also tried ...
315
votes
13
answers
239k
views
How to run Jest tests sequentially?
I'm running Jest tests via npm test. Jest runs tests in parallel by default. Is there any way to make the tests run sequentially?
I have some tests calling third-party code which relies on changing ...
299
votes
5
answers
323k
views
How can I clear the Jest cache?
Jest is picking up an old version of a package and thus my tests fail unless I use --no-cache. I can even delete the package folder from folder node_modules and Jest is happy to run the tests (almost ...
291
votes
6
answers
330k
views
How can I test for object keys and values equality using Jest?
I have a mapModule where I import components and export them:
import ComponentName from '../components/ComponentName';
export default {
name: ComponentName,
};
How can I test that mapModule has ...
289
votes
15
answers
214k
views
Better way to disable console inside unit tests
I wonder if there is a better way to disable console errors inside a specific Jest test (i.e. restore the original console before/after each test).
Here is my current approach:
describe("Some ...
273
votes
6
answers
315k
views
How to reset Jest mock functions calls count before every test
I'm trying to use it for testing if a function was called or not. I noticed the mock.calls.length is not resetting for every test but accumulating. How can I make it 0 before every test? I don't want ...
266
votes
31
answers
251k
views
How do I deal with localStorage in jest tests?
I keep getting "localStorage is not defined" in Jest tests which makes sense but what are my options? Hitting brick walls.
263
votes
8
answers
227k
views
How to change mock implementation on a per single test basis?
I'd like to change the implementation of a mocked dependency on a per single test basis by extending the default mock's behaviour and reverting it back to the original implementation when the next ...
259
votes
21
answers
290k
views
Jest gives an error: "SyntaxError: Unexpected token export"
I'm using Jest to test my React app.
Recently, I added DeckGL to my app. My tests fail with this error:
Test suite failed to run
/my_project/node_modules/deck.gl/src/react/index.js:21
export {default ...
256
votes
17
answers
395k
views
How can I mock the JavaScript 'window' object using Jest?
I need to test a function which opens a new tab in the browser
openStatementsReport(contactIds) {
window.open(`a_url_${contactIds}`);
}
I would like to mock window's open function, so I can verify ...
254
votes
19
answers
299k
views
react-testing-library why is toBeInTheDocument() not a function
Here is my code for a tooltip that toggles the CSS property display: block on MouseOver and on Mouse Out display: none.
it('should show and hide the message using onMouseOver and onMouseOut events ...
254
votes
6
answers
191k
views
Loose match one value in jest.toHaveBeenCalledWith
I have an analytics tracker that will only call after 1 second and with an object where the intervalInMilliseconds (duration) value is not deterministic.
How can I use jest.toHaveBeenCalledWith to ...
252
votes
7
answers
183k
views
Mock only one function from module but leave rest with original functionality
I only want to mock a single function (named export) from a module but leave the rest of the module functions intact.
Using jest.mock('package-name') makes all exported functions mocks, which I don't ...
251
votes
7
answers
222k
views
How can I get the arguments called in jest mock function?
How can I get the arguments called in jest mock function?
I want to inspect the object that is passed as argument.
248
votes
38
answers
246k
views
Cannot find name 'describe'. Do you need to install type definitions for a test runner?
When using TypeScript in conjunction with Jest, my specs would fail with error messages like:
test/unit/some.spec.ts:1:1 - error TS2582: Cannot find name 'describe'. Do you need to install type ...
233
votes
24
answers
180k
views
Jest test fails : TypeError: window.matchMedia is not a function
This is my first front-end testing experience. In this project, I'm using Jest snapshot testing and got an error TypeError: window.matchMedia is not a function inside my component.
I go through Jest ...
232
votes
6
answers
207k
views
Skip one test in test file Jest
I'm using Jest framework and have a test suite. I want to turn off/skip one of my tests.
Googling documentation doesn't give me answers.
Do you know the answer or source of information to check?
232
votes
15
answers
240k
views
Mock dependency in Jest with TypeScript
When testing a module that has a dependency in a different file and assigning that module to be a jest.mock, TypeScript gives an error that the method mockReturnThisOnce (or any other jest.mock method)...
231
votes
12
answers
225k
views
react-testing-library: some portion of debug's output is not visible
I am using react jest with react testing library to test my component.
I am facing a weird issue. I am using debug, returned by render from testing-library.
test('component should work', async () =>...
226
votes
5
answers
179k
views
What is the difference between describe and it in Jest?
When writing a unit test in Jest or Jasmine when do you use describe?
When do you use it?
I usually do
describe('my beverage', () => {
test('is delicious', () => {
});
});
When is it time ...
225
votes
11
answers
192k
views
Is there an Array equality match function that ignores element position in jest.js?
I get that .toEqual() checks equality of all fields for plain objects:
expect(
{"key1":"pink wool","key2":"diorite"}
).toEqual(
{"key2":"...
224
votes
4
answers
328k
views
How to properly make mock throw an error in Jest?
I'm testing my GraphQL api using Jest.
I'm using a separate test suit for each query/mutation
I have 2 tests (each one in a separate test suit) where I mock one function (namely, Meteor's callMethod)...
221
votes
11
answers
269k
views
Jest: How to mock one specific method of a class
Let's suppose I have the following class:
export default class Person {
constructor(first, last) {
this.first = first;
this.last = last;
}
sayMyName() {
console....
209
votes
12
answers
219k
views
Jest.js error: "Received: serializes to the same string"
I've having a strange problem with this test:
deal.test.js
import Deal from "../src/models/Deal";
import apiProducts from "../__mocks__/api/products";
describe("Deal", ()...
209
votes
8
answers
245k
views
How to mock imported named function in Jest when module is unmocked
I have the following module I'm trying to test in Jest:
// myModule.js
export function otherFn() {
console.log('do something');
}
export function testFn() {
otherFn();
// do other things
}
...
207
votes
13
answers
172k
views
Does Jest support ES6 import/export?
If I use import/export from ES6 then all my Jest tests fail with error:
Unexpected reserved word
I convert my object under test to use old school IIFE syntax and suddenly my tests pass. Or, take an ...
206
votes
16
answers
361k
views
Jest gives `Cannot find module` when importing components with absolute paths
Receiving the following error when running Jest
Cannot find module 'src/views/app' from 'index.jsx'
at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:179:17)
at Object.<...
203
votes
6
answers
200k
views
How to reset or clear a spy in Jest?
I have a spy that is used in multiple assertions across multiple tests in a suite.
How do I clear or reset the spy so that in each test the method that the spy intercepts is considered not to have ...
203
votes
20
answers
293k
views
Jest won't transform the module - SyntaxError: Cannot use import statement outside a module
I couldn't get rid of this SyntaxError: Cannot use import statement outside a module error no matter what I have tried and it got so frustrating. Is there anybody out here solved this issue? I have ...
202
votes
32
answers
238k
views
Property 'toBeInTheDocument' does not exist on type 'Matchers<any>'
I'm trying to write tests for my simple React App that creates a UI for a dog Shelter using API etc. I have imported the modules shown below and ran the following command
npm install jest-dom react-...
202
votes
22
answers
282k
views
How to mock window.location.href with Jest + Vuejs?
Currently, I am implementing unit tests for my project and there is a file that contains window.location.href.
I want to mock this to test and here is my sample code:
it("method A should work ...
200
votes
24
answers
160k
views
Absolute paths (baseUrl) gives error: Cannot find module
I am setting a configuration to run my tests in a create-react-app + typescript app (from which I have ejected). I am using jest + enzyme. In my tsconfig.json I have set baseUrl='./src' so I can use ...
194
votes
10
answers
480k
views
How to test a className with the Jest and React testing library
I am totally new to JavaScript testing and am working in a new codebase. I would like to write a test that is checking for a className on the element. I am working with Jest and React Testing Library. ...
193
votes
8
answers
233k
views
Run only ONE test with Jest
I want to run just one test with Jest.
I use it.only or describe.only, but it still runs a whole lot of tests. I think it runs all the tests since my last commit, but it shouldn't have this behavior ...
193
votes
15
answers
97k
views
How to add custom message to Jest expect?
Image following test case:
it('valid emails checks', () => {
['[email protected]', '[email protected]'/*, ...*/].map(mail => {
expect(isValid(mail)).toBe(true);
});
});
I would like to add auto-generated ...
191
votes
6
answers
164k
views
What is the difference between 'toBe' and 'toEqual' in Jest?
Jest documentation reads:
toBe just checks that a value is what you expect. It uses === to check strict equality.
And for toEqual:
Use .toEqual when you want to check that two objects have the ...
183
votes
13
answers
254k
views
How can I exclude files from Jest watch?
I'm doing some slightly bizarre stuff using Jest for testing where I'm writing some stuff to disk. If I use the watch flag in Jest however then I'm finding (quite obviously) that each time I write ...