【问题标题】:How to spy on default prop function in Jest如何在 Jest 中监视默认道具功能
【发布时间】:2020-02-03 01:25:20
【问题描述】:

我正在尝试测试一个函数类型的默认道具,但不确定如何使用 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();
        });

它说 TypeError: Cannot assign to read only property 'toggle' of object '[object Object]' 其中toggle是InfoModal的默认属性的函数。

我们如何测试一个已经设置为默认值而不是用户定义的函数属性。

【问题讨论】:

  • 您可以访问 defaultProp 之类的; InfoModal.defaultProps.function

标签: reactjs jestjs enzyme


【解决方案1】:

你可以像静态道具一样访问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()

已编辑:

你可以这样监视它;

const spy = jest.spyOn(App.defaultProps, 'check');
const RenderedApp = shallow(<App />);
RenderedApp.simulate('click');
expect(spy).toHaveBeenCalled();

所以改变这一行

const fn = jest.spyOn(wrapper.props(), "toggle");

const fn = jest.spyOn(wrapper.defaultProps, "toggle");

将为您解决问题。

https://codesandbox.io/s/zen-morning-881ny

【讨论】:

  • 这很好,但是如何密切关注这个函数以检查它是否在模拟组件上的某些事件后被调用。
  • 查看我的回答,希望对您有所帮助
猜你喜欢
  • 2019-06-12
  • 2019-11-01
  • 2018-05-26
  • 1970-01-01
  • 1970-01-01
  • 2019-12-25
  • 2021-08-13
  • 2020-12-21
  • 2019-06-15
相关资源
最近更新 更多