Suppose in my util.js I have
export function foo(){ ... do something}
export function bar(){ ... do something}
...
And in various ponents I utilize foo
//Foo1ponent.js
import { foo } from './util'A
... do something using foo.
//Foo2ponent.js
import { foo } from './util'A
... do something using foo.
etc..
How can I go about mocking this, in Foo1.test.js
for example.
Even better, is there way that I can just 'hijack' this foo
import maybe from the jest.config.
in the moduleNameMapper
Maybe?
So that it is already mocked for all tests Foo1.test.js
and Foo2.test.js
?
Suppose in my util.js I have
export function foo(){ ... do something}
export function bar(){ ... do something}
...
And in various ponents I utilize foo
//Foo1.ponent.js
import { foo } from './util'A
... do something using foo.
//Foo2.ponent.js
import { foo } from './util'A
... do something using foo.
etc..
How can I go about mocking this, in Foo1.test.js
for example.
Even better, is there way that I can just 'hijack' this foo
import maybe from the jest.config.
in the moduleNameMapper
Maybe?
So that it is already mocked for all tests Foo1.test.js
and Foo2.test.js
?
-
To create a single, global mock for all tests, you can use the
setupFiles
config settingjest.config.js
as described this answer. For partially mocking a module, see jestjs.io/docs/mock-functions#mocking-partials. – Hawkeye Parker Commented Apr 24, 2024 at 19:05
1 Answer
Reset to default 4Yes, there is a way to mock modules in test environment.
If you want to mock the modules in specific test files, you can try just the jest.mock()
function. For example, mocking the foo
method in Foo1.ponent.js
test file would go like this:
// Foo1.ponent.test.js
jest.mock('./path/to/utils.js', () => ({
foo: () => { // custom implementation for test env }
bar: () => { // custom implementation for test env if needed }
}));
// The foo imported below has the custom implementation for test env
import { foo } from './util';
The other option is to create a mock module, I think this better suite your need. In the folder where utils.js
is located, create a __mocks__
folder, under which you would add a file utils.js
(the same name as the module to be mocked), in that file, you can pose the mock behavior for the util.js
module. For example:
// __mocks__/utils.js
export function foo(){ ... mock implementation}
export function bar(){ ... mock implementation}
Whenever you need those mock implementation in your test files, just call the the jest.mock
method with the path to the module. For example:
// Foo1.ponent.test.js
jest.mock('./path/to/utils.js');
// The foo imported below has the custom implementation for test env
import { foo } from './util';
Links:
- Using
jest.mock
- Creating mock modules
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745348386a4623674.html
评论列表(0条)