Javascript 测试按钮';使用withRouter包装组件的状态
我有一个组件当前使用withRouter包装(例如,我使用了导出默认withRouter(myComponent)),因为我需要使用历史记录。推送组件中的一个链接。我正在用Ezyme编写一个测试,测试当用户单击该组件中的按钮时,该按钮是否会将其状态更改为true/false。测试失败,错误是无法读取isExpanded的属性null。这是我考试的内容:Javascript 测试按钮';使用withRouter包装组件的状态,javascript,reactjs,enzyme,Javascript,Reactjs,Enzyme,我有一个组件当前使用withRouter包装(例如,我使用了导出默认withRouter(myComponent)),因为我需要使用历史记录。推送组件中的一个链接。我正在用Ezyme编写一个测试,测试当用户单击该组件中的按钮时,该按钮是否会将其状态更改为true/false。测试失败,错误是无法读取isExpanded的属性null。这是我考试的内容: import React from 'react'; import Adapter from 'enzyme-adapter-react-16'
import React from 'react';
import Adapter from 'enzyme-adapter-react-16';
import { mount, configure } from 'enzyme';
import { MemoryRouter } from 'react-router-dom';
import myComponent from './myComponent';
configure({ adapter: new Adapter() });
describe('Successful flows', () => {
test('button changes state when clicked', () => {
const wrapper = mount(<MemoryRouter><myComponent /></MemoryRouter>);
const moreBtn = wrapper.find('.seeMoreButton').at(0);
moreBtn.simulate('click');
expect(wrapper.state().isExpanded).toEqual(true);
});
});
从“React”导入React;
从'enzyme-Adapter-react-16'导入适配器;
从“酶”导入{mount,configure};
从'react router dom'导入{MemoryRouter};
从“/myComponent”导入myComponent;
配置({adapter:newadapter()});
描述('成功流',()=>{
测试('单击按钮时更改状态',()=>{
const wrapper=mount();
const moreBtn=wrapper.find('.seeMoreButton')。位于(0);
moreBtn.simulate('click');
expect(wrapper.state().isExpanded).toEqual(true);
});
});
我发现,在我使用路由器之前,我刚刚使用了
const wrapper=mount()代码>在我的测试中,测试通过。我对路由相当陌生,我觉得这里缺少了一些东西,因此非常感谢您的帮助。您正在检查错误组件的状态,装载的结果将是MemoryRouter
,而不是myComponent
挂载组件后,您需要找到myComponent
,并验证其状态
test('button changes state when clicked', () => {
const wrapper = mount(<MemoryRouter><myComponent /></MemoryRouter>);
const comp = wrapper.find(myComponent);
const moreBtn = comp.find('.seeMoreButton').at(0);
moreBtn.simulate('click');
expect(comp.state().isExpanded).toEqual(true);
});
test('按钮单击时改变状态',()=>{
const wrapper=mount();
const comp=wrapper.find(myComponent);
const moreBtn=comp.find('.seeMoreButton')。位于(0);
moreBtn.simulate('click');
expect(comp.state().isExpanded).toEqual(true);
});
当我这样做时,会出现错误“ReactWrapper::state()只能在类组件上调用”@PythonSOS,这是一个与测试HOCs相关的问题。