简体   繁体   English

如何监视在componentDidMount内部调用的方法

[英]How to spy on a method which is called inside componentDidMount

I am trying to spy on a method which is called inside componentDidMount. 我正在尝试监视一个在componentDidMount内部调用的方法。 The method itself resides inside another file. 该方法本身位于另一个文件中。 Here is what i tried so far: 这是我到目前为止尝试过的:

import apicall from './AnotherFile'
class MyComponent {
    componentDidMount() {
        apicall()
    }
    <other code ->
}

Test: 测试:

const wrapper = mount(<MyComponent/>);
const instance = wrapper.instance();
jest.spyOn(instance, 'apicall');
instance.componentDidMount();
expect(instance.apicall).toHaveBeenCalled();

It gives an error: 它给出了一个错误:

Cannot spy the apicall property because it is not a function; undefined given instead

Any idea how this can be achieved ? 知道如何实现吗?

There are a few ways you can do this: 有几种方法可以执行此操作:

  1. Mock the import in your test file : By using jest.mock , Jest will intercept an import and create a mock version when it's used in the component file: 在测试文件中模拟导入 :通过使用jest.mock ,Jest将拦截导入并在组件文件中使用导入时创建模拟版本:

     // MyComponent.test.js import apicall from './AnotherFile' jest.mock('./AnotherFile'); it('makes API call', () => { const wrapper = mount(<MyComponent />); expect(apicall).toHaveBeenCalled(); }); 

No need to get the instance , no need to manually call componentDidMount , that will happen when you mount(<MyComponent />) . 无需获取instance ,无需手动调用componentDidMount ,这将在您mount(<MyComponent />) Note: if apicall should return a value or a promise, you can provide a mock value: 注意:如果apicall应该返回一个值或一个apicall ,则可以提供一个模拟值:

// Mock a response if your componentDidMount calls `apicall.then()`...
apicall.mockImplementation(() => Promise.resolve('some value'));
// Mock a rejected Promise to test error cases
apicall.mockImplementation(() => Promise.reject('Oh no!'));
  1. Dependency injection: Pass the apicall function into your component. 依赖注入:apicall函数传递到您的组件中。 You can make it default to the actual apicall you import, but in the test you can pass in a mock function: 您可以将其默认设置为导入的实际apicall ,但在测试中可以传递模拟函数:

     // MyComponent.js import apicall as realApiCall from './AnotherFile' class MyComponent extends Component { static defaultProps = { apicall: realApiCall } componentDidMount() { // This will call the real apicall if you don't provide // a prop: <MyComponent /> ... but allows you to inject // a mock apicall function in tests. this.props.apicall() } <other code -> } // MyComponent.test.js const apicall = jest.fn(); const wrapper = mount(<MyComponent apicall={apicall} />); expect(apicall).toHaveBeenCalled(); 

You mock the function that was imported. 您模拟导入的函数。 Try this 尝试这个

    import * as dependency from '../AnotherFile';

    describe('MyComponent', () => {
        it('test apicall', () => {
            dependency.apicall = jest.fn();

            const wrapper = mount(<MyComponent />);
            wrapper.instance().componentDidMount();

            expect(dependency.apicall).toHaveBeenCalled();
        });
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM