javascript - Jestjs如何测试在另一个函数中调用的函数
问题描述
对于测试,我使用 jest 和 react-test-renderer。它应该很容易测试,但是我很难找到合适的例子。我曾尝试做类似的事情(通常我将函数保存在单独的文件中):
实用程序.js
export const childFunction = () => 'something';
const parentFunction = () => childFunction();
export default parentFunction;
utils.test.js
import parentFunction from './utils.js';
it('childFunction should be called', () => {
const childFunction = jest.fn();
parentFunction();
expect(childFunction).toBeCalled();
})
片段const childFunction = jest.fn(); 绝对行不通。在调用时,parentFunction 的主体只关心它自己的作用域。但是,如果我导入 childFunction 并执行jest.mock(childFunction) ,它也不起作用,因为 jest.mock 需要一个字符串、一个模块的 url,而不是函数本身。
上面的示例不起作用,我正在寻找替代方法。但是,这在使用 ShallowRenderer 渲染组件后有效。而且我想通过嵌套在另一个函数中的函数来实现类似的行为。
class Component extends React.Component {
componentDidMount() {parentFunction()}
render() {...}
}
const renderer = new ShallowRenderer();
describe("testing parentFunction", () => {
renderer.render(<Component/>);
it("parentFunction should be called", () => {
expect(parentFunction).toBeCalled();
});
});
解决方案
不确定这是否会有所帮助,但它可能会给你一些想法。
首先,上面的例子:
// this needs to be stubbed
// const childFunction = () => 'something';
const childFunction = jest.fn();
const parentFunction = () => childFunction();
it('childFunction should be called', () => {
parentFunction();
expect(childFunction).toHaveBeenCalled();
}
这是一个有些人为的示例,因为它不太可能childFunction
被导出,因此您无法获得对它的引用并对其进行模拟/存根。
您拥有的一种解决方法是将其移出到自己的方法中
class Component extends React.Component {
componentDidMount() {
this.parentFunction();
}
parentFunction() {
parentFunction(); // from elsewhere
}
render() {...}
}
这允许您在组件原型上创建穿刺和间谍。
例如
const spy = jest.spyOn(Component.prototype, 'parentFunction');
// ... mount so lifecycle runs...
expect(spy).toHaveBeenCalled(); // and clear the spy mocks after!
模拟模块可能会更好
例如,您的组件使用了 utils.js,它执行以下操作:
export function parentFunction(){ console.log('parent'); }
component.js 会:
import { parentFunction } from './utils';
你可以在你的测试中做:
const utils = require('./utils');
utils.parentFunction = jest.fn();
import Component from './component';
// later
expect(utils.parentFunction).toHaveBeenCalled();
如您所见,有很多可能的方法,尽管我不确定该测试的价值,但您可能应该测试组件的输出/功能而不是它已调用,运行某些东西componentDidMount
是给定的,并且只会如果有人转换为功能性或更改了生命周期名称,则中断。
推荐阅读
- flutter - 在颤振中重新启动(再次关闭和打开)后对话框状态不会改变
- docker - docker.service:服务缺少 ExecStart= 和 ExecStop= 设置。拒绝
- android - Android:如何显示多个设备的当前位置?
- ibm-cloud - 现在(2020 年 12 月 19 日)有没有办法访问 IBM 云沃森个性洞察服务?
- python - 使用导入时函数未定义错误
- flutter - 颤振状态恢复与共享偏好有何不同?
- c++ - 这个问题的输出是正确的,但我得到一个分段错误
- python - PIL ImageDraw.Draw() 根本不画线
- nim-lang - 人生游戏运行缓慢
- css - Shiny - 加载时在应用程序上显示 CSS 样式表