Man*_*gir 5 reactjs jestjs enzyme
我正在尝试测试一个函数类型的默认道具,但不确定如何使用 Jest 模拟或间谍来做到这一点:
尝试以下测试:
it("should call default toggle function prop on click of footer button", () => {
const wrapper = shallow(
<InfoModal
isOpen={true}
message="Primary message"
secondaryMessage="Secondary message"
/>
);
const footerButton = wrapper.find("ModalFooter Button");
const fn = jest.spyOn(wrapper.props(), "toggle");
footerButton.simulate("click");
wrapper.update();
expect(fn).toHaveBeenCalled();
});
Run Code Online (Sandbox Code Playgroud)
它说TypeError:无法分配给对象“[object Object]”的只读属性“toggle”,其中 toggle 是作为InfoModal.
我们如何测试已设置为默认值而非用户定义的函数 prop。
您可以像静态道具一样访问defaultProps;
function App() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
App.defaultProps = {
check: () => console.log('i am working')
}
App.defaultProps.check()
Run Code Online (Sandbox Code Playgroud)
编辑:
你可以像这样监视它;
const spy = jest.spyOn(App.defaultProps, 'check');
const RenderedApp = shallow(<App />);
RenderedApp.simulate('click');
expect(spy).toHaveBeenCalled();
Run Code Online (Sandbox Code Playgroud)
所以改变这一行
const fn = jest.spyOn(wrapper.props(), "toggle");
Run Code Online (Sandbox Code Playgroud)
到
const fn = jest.spyOn(wrapper.defaultProps, "toggle");
Run Code Online (Sandbox Code Playgroud)
会为你解决这个问题。
https://codesandbox.io/s/zen-morning-881ny
| 归档时间: |
|
| 查看次数: |
903 次 |
| 最近记录: |