unit-testing - 模拟命名导出以使用 Jest 进行测试
问题描述
我有一个Helper.js
文件,其中包含以下几个帮助函数,这些函数正在不同的组件中使用。
export function buildOptions(elem) {
var oList=[];
for (var i=0; i < field.length; i++) {
oList.push (
<option value={options[i]["id"]}>
{options[i][elem]}
</option>
)
}
return oList;
}
export function B(){
.....
}
这是一个使用Helper.js
文件中定义的函数的组件。我正在为组件编写测试,我想模拟这里调用的外部函数。
import React from 'react';
import ReactDOM from 'react-dom';
import { buildOptions, A} from './Helper.js';
class DemoComponent extends React.Component {
constructor(props) {
super(props);
}
add(e, index) {
....
}
render() {
var o_list=buildOptions("name");
return (
<div>
...
<select required className={selectClass} >
{o_list}
</select>
...
<button type="button" onClick={(e) => this.add(e, this.props.index)}>
Add
</button>
</div>
);
};
}
我是 Jest/Enzyme 的新手,我无法弄清楚如何模拟外部函数 buildOptions。我无法弄清楚如何模拟外部 buildOptions 函数。有人可以帮我解决这个问题吗?这是我的测试代码:
import React from 'react';
import { mount, shallow } from 'enzyme';
import { buildOptions } from '../components/Helper.js';
import DemoComponent from '../components/DemoComponent';
describe('Democomponent', () => {
it('should render required elements', () => {
const wrapper = shallow(
<DemoComponent
index={0}/>
);
//
tests
});
解决方案
因为你想模拟一个命名的导出函数,所以有一个特殊的技巧,它涉及在你的测试之前使用一个导入所有命名的导出。*
// your test file
import * as Helper from './Helper.js';
const originalBuildOptions = Helper.buildOptions;
Helper.buildOptions = jest.fn();
beforeEach(() => {
jest.clearAllMocks();
// Reset to original implementation before each test
Helper.buildOptions.mockImplementation(originalBuildOptions);
});
test('my test', () => {
// Mock for this test only (will be restored by next `beforeEach` call)
Helper.buildOptions.mockImplementation(() => 'your mock');
});
推荐阅读
- c++ - 如何在 C++ 中使用类和对象重载 << 运算符
- c# - 将 JSON 从 AJAX 发送到控制器类
- regex - 正则表达式模式来捕获一段字符串
- reactjs - 钩子的 React.js 同步问题。连接四个游戏移动
- azure-devops-rest-api - azure-devops-node-api:如何在 ProjectCollection 范围内设置DocumentByName
- css - 为 iphone 调整图像大小
- javascript - React JS 期望一个赋值或函数调用,而是看到一个表达式
- python - 安装 Adafruit 软件后 SPI 总线不工作
- java - 我的应用程序在 Android Studio 上的 Android Emulator 上启动后立即崩溃
- flutter - 如何在 Flutter 中更改 Drawer 的整个背景颜色