Jest:当同一模块也命名为export时,如何模拟默认导出组件?

bea*_*ean 16 javascript unit-testing reactjs jestjs es6-modules

我有一个ES6模块,默认情况下导出一个React Component类,但也导出一个普通的JS函数作为命名导出.在测试使用此模块的其他软件包时,我想模拟默认导出组件和命名导出函数,以保持单元测试的纯净.

该模块看起来像这样:

import React, { Component } from 'react';

export default class MyComponent extends Component {
  render() {
    return <div>Hello</div>
  }
}

export function myUtilityFunction() { return 'foo' };
Run Code Online (Sandbox Code Playgroud)

我想使用以下语法来模拟导出:

import React from 'react';
import MyComponent, { myUtilityFunction } from './module';

jest.mock('./module');
MyComponent.mockImplementation(() => 'MockComponent');
myUtilityFunction.mockImplementation(() => 'foo');
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试使用此语法时,在其他组件中使用时,MyComponent似乎不会被模拟.当我尝试像这样模拟MyComponent并自己渲染它时,它会呈现为null.

这种行为很奇怪,因为如果我使用完全相同的语法,但两个导入都是JavaScript函数,则模拟按预期工作.请参阅我在此处打开的StackOverflow问题,该问题确认当导入都是函数时语法有效.

这是一个演示问题的GitHub仓库,以及我尝试过的几个解决方案:https://github.com/zpalexander/jest-enzyme-problem

您可以构建repo并使用yarn install && yarn test运行测试

谢谢!

Alb*_*ivé 6

另一种解决方案对我不起作用.这就是我做的:

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

另一种方法:

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

const myModule = require('../src/dependency');
myModule.utilityFunction = 'your mock'
Run Code Online (Sandbox Code Playgroud)


小智 4

我认为问题在于 ShallowWrapper 类的 getElement 方法需要传递一个包含 render 方法的类。为此,您的 MyComponent.mockImplementation 需要更全面地模拟类构造函数。

有关如何模拟类构造函数的详细信息,请参阅从“mockImplementation 也可用于模拟类构造函数:”开始的 Jest 文档https://facebook.github.io/jest/docs/en/mock-function-api。 html#mockfnmockimplementationfn

使用 Jest 文档作为模型,我们可以模拟 MyComponent 类构造函数,并通过酶使其可浅层渲染,如下所示:

MyComponent.mockImplementation(() => {
  return {
    render: () => <div>MockComponent</div>
  };
});
Run Code Online (Sandbox Code Playgroud)

现在,当 getElement 寻找渲染方法时,它会找到它。

以下是在您的存储库中的 App.mockImplementation.test.js 文件上实现此更改的要点:https://gist.github.com/timothyjellison/a9c9c2fdfb0b30aab5698dd92e901b24