Jest: How to mock default export Component when same module also has named export?

我的梦境 提交于 2019-12-04 22:59:57

I think the issue is that the ShallowWrapper class's getElement method needs to be passed a class that contains a render method. To do that, your MyComponent.mockImplementation needs to more fully mock a class constructor.

For details on how to mock a class constructor, see the Jest documentation starting at "mockImplementation can also be used to mock class constructors:" https://facebook.github.io/jest/docs/en/mock-function-api.html#mockfnmockimplementationfn

Using the Jest documentation as a model, we can mock the MyComponent class constructor and make it shallow renderable by enzyme like this:

MyComponent.mockImplementation(() => {
  return {
    render: () => <div>MockComponent</div>
  };
});

Now when getElement goes looking for a render method it will find it.

Here's a gist that implements this change on the App.mockImplementation.test.js file from your repo: https://gist.github.com/timothyjellison/a9c9c2fdfb0b30aab5698dd92e901b24

The other solution didn't work for me. This is how I did:

  jest.mock('./module', () => ({
    __esModule: true,
    myUtilityFunction: 'myUtilityFunction',
    default: 'MyComponent'
  }));

Another way to do it:

jest.unmock('../src/dependency');

const myModule = require('../src/dependency');
myModule.utilityFunction = 'your mock'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!