reactjs - 在功能组件玩笑中断言 onBlur() 函数
问题描述
我写了一个测试用例来调用onBlur
方法,但是当我尝试断言它时出现错误。这是上面的测试用例。
it("call the handlingBlurEmail method", () => {
const wrapper = mount(
<App childRef={() => {}} />
);
const comp = wrapper.find({ id: "email" }).first();
comp.prop("onBlur")({
target: { id: "email", value: "test@gmail.com" }
});
expect(
wrapper
.find("AccountForm")
.state()
.onBlur()
).toHaveBeenCalled();
});
我正在为其编写测试用例的功能是
mailReference = React.createRef();
handlingEmailBlur = events => {
this.mailReference.current.validate(events.target.value);
};
render = () {
......
return (
<div className="Form1">
onBlur={this.handlingEmailBlur}
</div>
)
.....
}
请让我知道如何添加断言语句以调用onBlur()
上述测试用例中的方法
解决方案
这是单元测试解决方案:
index.tsx
:
import React, { Component } from 'react';
class App extends Component {
mailReference = React.createRef();
handlingEmailBlur = (events) => {
this.mailReference.current.validate(events.target.value);
};
render() {
return (
<div className="Form1" onBlur={this.handlingEmailBlur}>
some component
</div>
);
}
}
export default App;
index.spec.tsx
:
import App from './index';
import { mount } from 'enzyme';
import React from 'react';
describe('59455504', () => {
afterEach(() => {
jest.restoreAllMocks();
});
it('call the handlingBlurEmail method', () => {
const mailReference = { current: { validate: jest.fn() } };
jest.spyOn(React, 'createRef').mockReturnValue(mailReference);
const wrapper = mount(<App childRef={() => {}} />);
const mEvent = {
target: { id: 'email', value: 'test@gmail.com' },
};
wrapper.find('.Form1').prop('onBlur')(mEvent);
expect(mailReference.current.validate).toBeCalledWith(mEvent.target.value);
});
});
覆盖率 100% 的单元测试结果:
PASS src/stackoverflow/59455504/index.spec.jsx (8.328s)
59455504
✓ call the handlingBlurEmail method (40ms)
-----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.jsx | 100 | 100 | 100 | 100 | |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 9.769s
源代码:https ://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59455504
推荐阅读
- arrays - 声明为指针的数组存储在哪里?
- java - 没有为参数 1 指定值 - 查询是否太长?
- java - 用整数减去 java.util.Date
- r - 如何过滤面板数据以仅包括参与所有年份的人?
- aspnetboilerplate - ABP 中的 JWT 身份验证
- ios - 放大/缩小整个 Tableview
- android - 具有 UNIQUE KEY 约束的房间迁移不起作用
- javascript - 无法使用 npm 在 macOS 上安装 vue
- ios - UILabel 没有正确地将文本包裹在里面
- python - 在 Anaconda 提示符下安装 Jupyter Notebook 时出错