javascript - 反应酶无法测试点击功能
问题描述
] 1
这是我在该图像和测试代码中的整个组件代码
import React from 'react';
import Enzyme, { shallow, mount } from 'enzyme';
import ProfileCard from '../profileCard';
import Adapter from 'enzyme-adapter-react-16';
import InfoCard from '../infoCard';
import renderer from 'react-test-renderer';
Enzyme.configure({
adapter: new Adapter()
});
describe('Profile Card', () => {
const props = {
percentageCompleted: 20,
toggleModalVisibility: () => console.log(''),
title: 'Value From Test',
icon: 'string',
active: false
};
const component = mount(<InfoCard {...props} />);
it('onclick function should toggle model visibality', () => {
const wrapper = shallow(<InfoCard {...props} />).instance();
const preventDefaultSpy = jest.fn();
expect(component.props().title.length).toBe(15);
//wrapper.onClick //i am stuck here
console.log('what is in there', wrapper);
});
// it('should render correctly', () => {
// const tree = renderer.create(<InfoCard {...props} />).toJSON();
// expect(tree).toMatchSnapshot();
// });
it('icon shpuld be equal to prop icon', () => {
expect(component.find('img').prop('src')).toEqual(props.icon);
});
});
因为我不知道如何测试 onClick 功能。在函数中,我没有将参数或其他东西作为参数传递给函数。那么我该如何测试这个功能。对不起我的英语,因此我有点沮丧。
解决方案
首先我很抱歉,因为我只知道如何在 React Functions 中开发。但这里有一个 MVP 来测试onClick
功能。你只需要在toggleModalVisibility
and上断言title
。
您需要模拟toggleModalVisibility
,然后找到元素(在您的情况下为div
)并执行模拟事件(click
)并在那里进行断言。您无需担心该类文件中的实现细节,因为这无关紧要,您只关心预期的输出。
import { shallow } from "enzyme";
import React from "react";
import Enzyme from "enzyme";
import Adapter from "enzyme-adapter-react-16";
import InfoCard from "../src/InfoCard";
Enzyme.configure({ adapter: new Adapter() });
const toggleModalVisibility = jest.fn();
const initialProps = {
toggleModalVisibility,
title: "My title",
active: true
};
const getInfoCard = () => {
return shallow(<InfoCard {...initialProps} />);
};
let wrapper;
beforeEach(() => {
toggleModalVisibility.mockClear();
});
it("should call toggleModalVisiblity when onClick", () => {
wrapper = getInfoCard();
wrapper.find("div#myDiv").simulate("click");
expect(toggleModalVisibility).toHaveBeenCalledWith(initialProps.title);
});
推荐阅读
- jquery - 重力形式:AJAX 加载的复选框在错误验证时未选中
- javascript - JQuery insertBefore()重复插入
- c# - .net 非托管内存泄漏
- php - 我如何测试一个 Laravel 工作在测试中分派另一个工作?
- flutter - 如何在列表中进行复选框选择、取消选择和全部选择?
- java - 带宽共享(master => workers)
- cookies - Outlook Web 插件 - 关闭任务窗格时清除 cookie win 10
- excel - 使用索引将所有在 col A 中有数量的行从所有工作表复制到 1 个工作表上
- c++ - 使用 powershell 我从 c++ 发送电子邮件并传递参数,如果第一个参数包含“测试邮件”,那么 powershell 将其作为 2 个参数
- docker - Docker-compose jupyterhub 问题