总结三种常见的Jest Mock方法:
1. Mock a method of module in test
// App.test.js
// 1. Import module
import api from '../../api'
// 2. Mock method
jest.mock('../../api', () => ({
getUser: jest.fn(),
}));
describe('App', () => {
test('Mock a method', async () => {
// 3. Return value
api.getUser.mockReturnValue(Promise.resolve(1010));
......
});
});
2. Mock constants variable
// constants.js
export const subject = {
name: '',
teacher: '',
}
// App.js
import { subject } from "./constants";
const App = () => {
...
const [subject, setSubject] = useState(subject);
...
}
export default App;
// App.test.js
// 1. Import file
import * as constants from './constants';
// 2. Override the variable object
Object.defineProperty(constants, 'subject', {
value: {
name: 'math',
teacher: 'A',
},
writable: true
});
// 3. Test conponment
it('test', () => {
wrapper = render(<App />);
...
});
3. Mock a hook method
// App.js
import {useToast} from "@moudle";
const App = () => {
...
const add = useToast()
add({message: 'test'})
...
}
export default App;
// App.test.js
// 1. MockAddToast
const mockAddToast = jest.fn();
jest.mock('@moudle"', () => ({
...jest.requireActual('@moudle"'),
useToast: () => mockAddToast,
}));
// 2. Test conponment
it('test', () => {
render(<App />);
expect(mockAddToast).toHaveBeenCalledTimes(1)
...
});
References