reactjs - 测试uisng酶时如何读取节点中的孩子
问题描述
我有一个组件,我想测试 click 方法。我正在使用浅,但我的测试失败了,因为它找不到按钮,因此它是点击方法。我的代码有什么问题?
interface IProps {
label: string;
className: string;
onClick: () => void;
}
export const NewButton: React.StatelessComponent<IProps> = props => {
return (
<Button type="button" className={props.className} onClick={props.onClick}>
{props.label}
</Button>
);
};
import { shallow } from 'enzyme';
import * as React from 'react';
import { NewButton } from "../Buttons";
describe('<NewButton />', () => {
describe('onClick()', () => {
const props = {
className: "buttonSubmit",
label: "submit",
onClick: () => {},
}
test('successfully calls the onClick handler', () => {
const mockOnClick = jest.fn();
const wrapper = shallow(
<NewButton {...props} />
);
const button = wrapper.find('submit').dive();
expect(button.exists()).toEqual(true)
button.simulate('click');
expect(mockOnClick.mock.calls.length).toBe(1);
});
});
});
解决方案
由于您使用的是shallow
方法,它只会渲染我们正在测试的组件。它不渲染子组件。因此,您应该尝试找到该Button
组件。
const button = wrapper.find('Button');
之后,您应该模拟props.onClick
作为道具传递给NewButton
组件的事件处理程序。
const props = {
className: "buttonSubmit",
label: "submit",
onClick: jest.fn(),
}
所以你可以使用
describe('<NewButton />', () => {
describe('onClick()', () => {
const props = {
className: "buttonSubmit",
label: "submit",
onClick: jest.fn(),
}
test('successfully calls the onClick handler', () => {
const wrapper = shallow(
<NewButton {...props} />
);
const button = wrapper.find('Button');
expect(button.exists()).toEqual(true)
button.simulate('click');
// Since we passed "onClick" as props
// we expect it to be called when
// button is clicked
// expect(props.onClick).toBeCalled();
expect(props.onClick.mock.calls.length).toBe(1);
});
});
});
推荐阅读
- python - Python struct 用反向字节序解压多个字节
- java - 在 Oracle 中获取不推荐使用的 StructDescriptor 的元数据
- sql - 将 varchar 值“xxx”转换为数据类型 int 时,函数错误中的光标转换失败
- browser-cache - 由于标头错误,响应没有被缓存
- javascript - 如何在angular2中调用具有相同功能的2个api
- reactjs - 使用clevertap-react-native npm 包,iOS 推送通知不起作用
- r - 将数据表中的行熔化或复制一定次数,并在 R 中包含计数器
- php - 为什么“创建方法”不在数据库中注册数据?
- php - 打包的电子应用程序如何使用 child_process?
- c# - 在 C# 中从平面列表创建嵌套列表