Testing
Testing
Jest
Config
Покрытие с одного файла
The solution is to add one small option --collectCoverageFrom
to collect only for a certain file (i.e. component).
yarn test my-component.test
--coverage
--collectCoverageFrom=src/components/my-component/my-component.tsx
Падать на упавших тестах
// jest.config.js
module.exports = {
// stop after first failing test
bail: true
// stop after 3 failed tests
bail: 3
}
Запуск по названию теста
Использовать флаг --testNamePattern
или -t
:
jest -t 'fix-order-test'
Mock
Reset mocks
beforeEach(() => {
jest.resetAllMocks();
});
Mock only one function from module
jest.mock('./utilities.js', () => ({
...jest.requireActual('./utilities.js'),
speak: jest.fn(),
}));
jest.mock("react", () => ({
...jest.requireActual("react"), // import and retain the original functionalities
useContext: jest.fn().mockReturnValue({foo: 'bar'}) // overwrite useContext
}))
For packages:
import axios from 'axios';
jest.spyOn(axios, 'get');
axios.get.mockImplementation(() => { /* do thing */ });
Mock default module
import dependency from 'dependency'
jest.mock('dependency', () => ({
...jest.requireActual('dependency'),
__esModule: true,
default: jest.fn(),
}))
Expect()
Expect async function to throw
it('should test async errors', async () => {
await expect(failingAsyncTest())
.rejects
.toThrow('I should fail');
});
Custom Error Class:
it("should test async errors", async () => {
await expect(asyncFunctionWithCustomError())
.rejects
.toBeInstanceOf(CustomError)
})
Ariakit Test Utils
https://twitter.com/ericclemmons/status/1573409650371973120?t=WYDGjaNLIqohX200TGt3Uw&s=19