a question for using Jest to mock a method from third party library. so I have a component implemented like this
import {foo} from 'bar'
function Component() {
// use foo somewhere in the component
}
and in the test I tried to mock out foo
, so
import {foo} from 'bar'
jest.mock('bar')
test('test', () => {
foo.mockReturnValue(...)
})
this works out fine but once I move jest.mock('bar')
into every individual test
block, jest would report an error saying that foo.mockReturnValue
is not a function. like this
test('test', () => {
jest.mock('bar')
foo.mockReturnValue(...) // 👈🏻 error: `foo.mockReturnValue` is not a function
})
The problem is that, I want to mock out bar
at every test
level, not the global level which affects the whole test file. is there a way to do that?
Since you want to mock out foo
at every test level, it makes more sense to keep bar
mocked globally and use beforeEach()
or afterEach()
to reset the mocked function before or after each test runs.
import {foo} from 'bar';
jest.mock('bar');
afterEach(() => {
foo.mockReset();
})
test('test', () => {
foo.mockReturnValue(...);
})
You'll want to use .mockReset()
to remove mocked implementations and return values from foo
; alternatively, .mockClear()
can be used if the implementation and return value for foo
remains the same for each test. Read more on the difference here .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.