模拟将出口命名为使用Jest进行测试 [英] Mock named exports for testing using Jest
问题描述
我有一个Helper.js
文件,其中包含以下几个辅助功能,这些文件正在不同的组件中使用.
I have a Helper.js
file with several helper functions as below that is being used in different components.
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
文件中定义的功能的组件.我正在为组件编写测试,我想模拟此处调用的外部函数.
Here is a component which makes use of the function defined in Helper.js
file. I am writing tests for the component and I would like to mock the external function being called here.
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函数.有人可以帮我这个忙. 这是我的测试代码:
I am new to Jest/Enzyme and I am unable to figure out how to mock the external function buildOptions. I am unable to figure out how to mock the external buildOptions function.Could anyone please help me with this. Here is my test code:
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
});
推荐答案
由于您要模拟命名的导出函数,因此有一个特殊的技巧,其中涉及导入所有命名的导出在测试之前输入*
.
Since you want to mock a named exported function, there is a special trick for that which involves importing all named exports with an *
before your 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');
});
这篇关于模拟将出口命名为使用Jest进行测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!