仅模拟模块中的一项功能,其余部分保留原始功能 [英] Mock only one function from module but leave rest with original functionality
问题描述
我只想从模块中模拟一个功能(命名为export),而其余模块功能保持完整.
I only want to mock a single function (named export) from a module but leave the rest of the module functions intact.
使用jest.mock('package-name')
可以模拟所有导出的函数,这是我所不希望的.
Using jest.mock('package-name')
makes all exported functions mocks, which I don't want.
我尝试将命名的出口传播回模拟对象中...
I tried spreading the named exports back into the mock object...
import * as utils from './utilities.js';
jest.mock(utils, () => ({
...utils
speak: jest.fn(),
}));
但出现此错误:
jest.mock()
的模块工厂不允许引用任何范围外的变量.
The module factory of
jest.mock()
is not allowed to reference any out-of-scope variables.
推荐答案
此答案的重点是 jest.requireActual(),这是一个非常有用的实用程序,可以说嘿".保持所有原始功能完整并导入".
The highlight of this answer is jest.requireActual(), this is a very useful utility that says to jest that "Hey keep every original functionalities intact and import them".
jest.mock('./utilities.js', () => ({
...jest.requireActual('./utilities.js'),
speak: jest.fn(),
}));
让我们采用另一种常见情况,您正在使用酶ShallowWrapper,但它与useContext()钩子配合得不太好,那么您要怎么做?虽然我确定有多种方法,但这是我喜欢的方法:
Let's take another common scenario, you're using enzyme ShallowWrapper and it doesn't goes well with useContext() hook, so what're you gonna do? While i'm sure there are multiple ways, but this is the one I like:
import React from "react";
jest.mock("react", () => ({
...jest.requireActual("react"), // import and retain the original functionalities
useContext: jest.fn().mockReturnValue({foo: 'bar'}) // overwrite useContext
}))
这样做的好处是您仍然可以使用
原始代码中的import React, { useContext } from "react"
,而不必担心将它们转换为 React.useContext(),就像使用 jest.spyOn(React,'useContext')一样
The perk of doing it this way is that you can still use
import React, { useContext } from "react"
in your original code without worrying about converting them into React.useContext() as you would if you're using jest.spyOn(React, 'useContext')
这篇关于仅模拟模块中的一项功能,其余部分保留原始功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!