How Do I Write Test Case For A Function Which Uses Uuid Using Jest?
I'm using jest for writing test cases. One of my function uses uuid and due to which it is not a pure function. The code is something like this: const myFunc = () => { const
Solution 1:
I have found this works really nice.
At the top of test file:
// your regular imports here
jest.mock('uuid', () => ({ v4: () =>'00000000-0000-0000-0000-000000000000' }));
// describe('test suite here', () => {
in the actual code:
import { v4 as uuidv4 } from'uuid';
Solution 2:
You can use jest.mock
inorder to mock the import of uuid
, like that:
const uuidMock = jest.fn().mockImplementation(() => {
return'my-none-unique-uuid';
});
jest.mock('uuid', () => {
return uuidMock;
});
The only caveat of that approach is that you need to apply the mock in the test file before you are importing your real file.
Then you will even able to assert on the mock.
For more info read jest.mock.
Post a Comment for "How Do I Write Test Case For A Function Which Uses Uuid Using Jest?"