您如何称呼酶的外部功能?

时间:2018-06-20 15:35:42

标签: reactjs unit-testing enzyme

我有一个标准的react组件,带有我正在调用或想要检查它们是否已被调用的外部函数

我知道我可以为类函数做wrapper.instance().funcName(),但是说我已经导入了外部函数,无论是作为prop还是作为直接导入,我该怎么做?

基本上我该如何做?

class component extends React.Component{

   localMethod = () => {
     externalMethod()
   }
}

expect(externalMethod).toHaveBeenCalled()

1 个答案:

答案 0 :(得分:0)

这将是您的组件,这很容易(但是您似乎不喜欢!对不起):
您的MyComponent 依赖于此外部方法
因此,为了易于测试,您的组件应允许注入这种依赖关系
这可以使您的测试为这种方法提供间谍。

您的测试代码:(紧随Arrange Act Assert Pattern之后)

// Arrange: create a jest spy
const externalMethodSpy = jest.fn();

wrapper = shallow(<MyComponent externalMethod={externalMethodSpy} />);
// Act on your wrapper ...

// Assert the result
expect(externalMethodSpy).toHaveBeenCalled();

您的生产代码:

class MyComponent extends React.Component{
   localMethod = () => {
     this.props.externalMethod()
   }
   ...
}