Jest coverage: How can I get a total percentage of coverage?

Thanks to Teneff’s answer, I go with the coverageReporter=”json-summary”. jest –coverage –coverageReporters=”json-summary” This generates a coverage-summary.json file which can easily be parsed. I get the total values directly from the json: “total”: { “lines”: { “total”: 21777, “covered”: 65, “skipped”: 0, “pct”: 0.3 }, “statements”: { “total”: 24163, “covered”: 72, “skipped”: 0, “pct”: 0.3 }, … Read more

Necessary to use expect.assertions() if you’re awaiting any async function calls?

expect.assertions is important when testing the error scenarios of asynchronous code, and is not redundant. If you remove expect.assertions from your example you can’t be confident that login did in fact throw the error. it(‘calls the API and throws an error’, async () => { try { await login(’email’, ‘password’); } catch (error) { expect(error.name).toEqual(‘Unauthorized’); … Read more

When should I use setupFiles rather than setupFilesAfterEnv?

We can see what different between setupFiles and setupFilesAfterEnv from the documentation. The most important difference will probably be when it is run. setupFiles will be executed before the test framework is installed in the environment. setupFilesAfterEnv will be executed after the test framework has been installed in the environment. That’s why the name has … Read more

Mock.mockImplementation() not working

I had same problem as @Janos, the other answers didn’t help either. You could do two things : If you need to mock only a function from Service, in your test file: import service from ‘./Service’; jest.mock(‘./Service’, () => jest.fn()); service.yourFunction = jest.fn(() => { /*your mock*/ })   If you need to mock the … Read more

Jest beforeAll() share between multiple test files

If you’re using Jest >=20, you might want to look into creating a custom jest-environment for the tests that require this common setup. This would be a module that extends either jest-environment-node or jest-environment-jsdom, and implements async setup(), async teardown(), and async runScript() to do this setup work. You can then add a @jest-environment my-custom-env … Read more

jest global variable example

Yep. You put the globals in the package.json. For example, here’s an excerpt from the default react-native jest configuration: “jest”: { “globals”: { “__DEV__”: true, “__RCTProfileIsProfiling”: false }, … }, This will make the variables available globally when the tests are run.