[我正在尝试编写一个使用酶来模拟按钮点击的测试,该测试期望触发onClick处理程序。我想用模拟代替组件的onClick处理程序。测试运行时,将调用组件类方法而不是模拟函数。任何指导将不胜感激!
下面是测试输出:
FAIL src/Form.test.js
● Console
console.log src/Form.js:5
this is from the component
● Submit handler called on click
expect(jest.fn()).toHaveBeenCalled()
Expected number of calls: >= 1
Received number of calls: 0
14 | submitButton.simulate("click");
15 |
> 16 | expect(onHandleSubmitMock).toHaveBeenCalled();
| ^
17 | });
18 |
at Object.<anonymous>.test (src/Form.test.js:16:30)
软件包版本:“开玩笑”:25.1.0“开胃菜酵素”:7.1.2“反应”:16.8.6
Form.js组件
import React, { Component } from "react";
export class Form extends Component {
onHandleSubmit = () => {
console.log("this is from the component");
};
render() {
return (
<div>
<button data-test="submit" onClick={this.onHandleSubmit}>
Submit
</button>
</div>
);
}
}
export default Form;
Form.test.js
import React from "react";
import { shallow } from "enzyme";
import Form from "./Form";
test("Submit handler called on click", () => {
const onHandleSubmitMock = jest.fn(() => console.log("mock was called"));
const wrapper = shallow(<Form />);
wrapper.instance().onHandleSubmit = onHandleSubmitMock;
wrapper.update();
const submitButton = wrapper.find(`[data-test="submit"]`);
submitButton.simulate("click");
expect(onHandleSubmitMock).toHaveBeenCalled();
});
原因是当浅层渲染Form
组件时,原始的onHandleSubmit
方法已经绑定到onClick
。因此,即使您将onHandleSubmitMock
分配给Form
组件的实例。晚了”。模拟click事件时,它将触发原始的onHandleSubmit
方法,而不是模拟的方法。
[如果您坚持用模拟的方法替换onHandleSubmit
方法。 您需要确保在浅渲染之前替换了该方法(绑定到onClick
)
例如form.jsx
:
import React from 'react';
import { shallow } from 'enzyme';
import Form from './form';
test('Submit handler called on click', () => {
const onHandleSubmitMock = jest.fn(() => console.log('mock was called'));
Form.prototype.onHandleSubmit = onHandleSubmitMock;
const wrapper = shallow(<Form />);
const submitButton = wrapper.find(`[data-test="submit"]`);
submitButton.simulate('click');
expect(onHandleSubmitMock).toHaveBeenCalled();
});
form.test.jsx
:
import React, { Component } from 'react';
export class Form extends Component {
constructor() {
this.onHandleSubmit = this.onHandleSubmit.bind(this);
}
onHandleSubmit() {
console.log('this is from the component');
}
render() {
return (
<div>
<button data-test="submit" onClick={this.onHandleSubmit}>
Submit
</button>
</div>
);
}
}
export default Form;
带有覆盖率报告的单元测试结果:
PASS stackoverflow/60138901/form.test.jsx (6.937s)
✓ Submit handler called on click (44ms)
console.log stackoverflow/60138901/form.test.jsx:6
mock was called
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 91.67 | 100 | 75 | 90 |
form.jsx | 91.67 | 100 | 75 | 90 | 8
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 8.65s