模拟函数·续1
expect(mockedFunction).toHaveBeenCalled()Expected mock function "mockedFunction" to have been called, but it was not called.
mockFn.mockReturnThis()
Syntactic sugar function for:
jest.fn(function () { return this;});
mockFn.mockReturnValue(value)
Accepts a value that will be returned whenever the mock function is called.
const mock = jest.fn();mock.mockReturnValue(42);mock(); // 42mock.mockReturnValue(43);mock(); // 43
mockFn.mockReturnValueOnce(value)
Accepts a value that will be returned for one call to the mock function. Accepts a value that will be returned for one call to the mock function. Can be chained so that successive calls to the mock function return different values. When there are no more mockReturnValueOnce values to use, calls will return a value specified by mockReturnValue. When there are no more mockReturnValueOnce values to use, calls will return a value specified by mockReturnValue.
const myMockFn = jest .fn() .mockReturnValue('default') .mockReturnValueOnce('first call') .mockReturnValueOnce('second call');// 'first call', 'second call', 'default', 'default'console.log(myMockFn(), myMockFn(), myMockFn(), myMockFn());
mockFn.mockResolvedValue(value)
Syntactic sugar function for:
jest.fn().mockImplementation(() => Promise.resolve(value));
Useful to mock async functions in async tests:
test('async test', async () => { const asyncMock = jest.fn().mockResolvedValue(43); await asyncMock(); // 43});
mockFn.mockResolvedValueOnce(value)
Syntactic sugar function for:
jest.fn().mockImplementationOnce(() => Promise.resolve(value));
Useful to resolve different values over multiple async calls:
test('async test', async () => { const asyncMock = jest .fn() .mockResolvedValue('default') .mockResolvedValueOnce('first call') .mockResolvedValueOnce('second call'); await asyncMock(); // first call await asyncMock(); // second call await asyncMock(); // default await asyncMock(); // default});
mockFn.mockRejectedValue(value)
Syntactic sugar function for:
jest.fn().mockImplementation(() => Promise.reject(value));
Useful to create async mock functions that will always reject:
test('async test', async () => { const asyncMock = jest.fn().mockRejectedValue(new Error('Async error')); await asyncMock(); // throws "Async error"});
mockFn.mockRejectedValueOnce(value)
Syntactic sugar function for:
jest.fn().mockImplementationOnce(() => Promise.reject(value));
Example usage:
test('async test', async () => { const asyncMock = jest .fn() .mockResolvedValueOnce('first call') .mockRejectedValueOnce(new Error('Async error')); await asyncMock(); // first call await asyncMock(); // throws "Async error"});
TypeScript
Jest itself is written in TypeScript.
If you are using Create React App then the TypeScript template has everything you need to start writing tests in TypeScript.
Otherwise, please see our Getting Started guide for to get setup with TypeScript.
You can see an example of using Jest with TypeScript in our GitHub repository.
jest.MockedFunction
jest.MockedFunction is available in the @types/jest module from version 24.9.0.
The following examples will assume you have an understanding of how Jest mock functions work with JavaScript.
You can use jest.MockedFunction to represent a function that has been replaced by a Jest mock.
Example using automatic jest.mock:
// Assume `add` is imported and used within `calculate`.// Assume `add` is imported and used within `calculate`.import add from './add';import calculate from './calc';jest.mock('./add');// Our mock of `add` is now fully typedconst mockAdd = add as jest.MockedFunction<typeof add>;test('calculate calls add', () => { calculate('Add', 1, 2); expect(mockAdd).toBeCalledTimes(1); expect(mockAdd).toBeCalledWith(1, 2);});
Example using jest.fn:
// Here `add` is imported for its typeimport add from './add';import calculate from './calc';test('calculate calls add', () => { // Create a new mock that can be used in place of `add`. // Here `add` is imported for its typeimport add from './add';import calculate from './calc';test('calculate calls add', () => { // Create a new mock that can be used in place of `add`. const mockAdd = jest.fn() as jest.MockedFunction<typeof add>; // Note: You can use the `jest.fn` type directly like this if you want: // const mockAdd = jest.fn<ReturnType<typeof add>, Parameters<typeof add>>(); // `jest.MockedFunction` is a more friendly shortcut. // Now we can easily set up mock implementations. // All the `.mock*` API can now give you proper types for `add`. // https://jestjs.io/docs/en/mock-function-api // `.mockImplementation` can now infer that `a` and `b` are `number` // and that the returned value is a `number`. mockAdd.mockImplementation((a, b) => { // Yes, this mock is still adding two numbers but imagine this // was a complex function we are mocking. return a + b })); // `mockAdd` is properly typed and therefore accepted by // anything requiring `add`. calculate(mockAdd, 1 , 2); expect(mockAdd).toBeCalledTimes(1); expect(mockAdd).toBeCalledWith(1, 2);}) // Now we can easily set up mock implementations. // All the `.mock*` API can now give you proper types for `add`. // https://jestjs.io/docs/mock-function-api // `.mockImplementation` can now infer that `a` and `b` are `number` // and that the returned value is a `number`. mockAdd.mockImplementation((a, b) => { // Yes, this mock is still adding two numbers but imagine this // was a complex function we are mocking. return a + b; }); // `mockAdd` is properly typed and therefore accepted by // anything requiring `add`. calculate(mockAdd, 1, 2); expect(mockAdd).toBeCalledTimes(1); expect(mockAdd).toBeCalledWith(1, 2);});
jest.MockedClass
jest.MockedClass is available in the @types/jest module from version 24.9.0.
The following examples will assume you have an understanding of how Jest mock classes work with JavaScript.
You can use jest.MockedClass to represent a class that has been replaced by a Jest mock.
Converting the ES6 Class automatic mock example would look like this:
