我试图模拟呼叫一个服务,但我用以下信息挣扎:The module factory of 100 is not allowed to reference any out-of-scope variables.

我正在使用babel与ES6语法、Jest 和Enzyme .

我有一个名为Vocabulary的简单组件,它从vocabularyService中获取VocabularyEntry个对象的列表,并对其进行渲染.

import React from 'react';
import vocabularyService from '../services/vocabularyService';

export default class Vocabulary extends React.Component {

render() {

    let rows = vocabularyService.vocabulary.map((v, i) => <tr key={i}>
            <td>{v.src}</td>
            <td>{v.target}</td>
        </tr>
    );
    // render rows
 }
 }

答案很简单:

  import {VocabularyEntry} from '../model/VocabularyEntry';

  class VocabularyService {

  constructor() {
       this.vocabulary = [new VocabularyEntry("a", "b")];
  }
} 
export default new VocabularyService();`

现在我想在一个测试中模拟vocabularyService:

import {shallow} from 'enzyme';
import React from 'react';
import Vocabulary from "../../../src/components/Vocabulary ";
import {VocabularyEntry} from '../../../src/model/VocabularyEntry'

jest.mock('../../../src/services/vocabularyService', () => ({

vocabulary: [new VocabularyEntry("a", "a1")]

}));

describe("Vocabulary tests", () => {

test("renders the vocabulary", () => {

    let $component = shallow(<Vocabulary/>);

    // expect something

});

});

运行测试会导致错误:词汇表.spec.js:babel plugin jest葫芦:jest.mock()的模块工厂不允许引用任何超出范围的变量.

就我所知,我无法使用VocabularyEntry,因为它不是声明的(因为jest将模拟定义移到了文件的顶部).

谁能解释一下我该怎么解决这个问题吗?我看到一些解决方案需要在模拟调用中引用,但我不明白如何使用类文件来实现这一点.

推荐答案

问题是,所有jest.mock个代码都将在编译时被提升到实际代码块的顶部,在本例中,这是文件的顶部.此时,VocabularyEntry未被导入.你可以在测试中把mock放在beforeAll块中,或者像这样使用jest.mock块:

import {shallow} from 'enzyme';
import React from 'react';
import Vocabulary from "../../../src/components/Vocabulary ";
import {VocabularyEntry} from '../../../src/model/VocabularyEntry'
import vocabularyService from '../../../src/services/vocabularyService'

jest.mock('../../../src/services/vocabularyService', () => jest.fn())

vocabularyService.mockImplementation(() => ({
  vocabulary: [new VocabularyEntry("a", "a1")]
}))

这将首先用一个简单的间谍模拟模块,在导入所有内容后,它将设置模拟的真正实现.

Reactjs相关问答推荐

构建next.js项目时状态不变,但在dev服务器中

在Redux工具包查询中,是否可以将标记应用到API切片内的所有端点?

如何在取数后添加新数据,并在页面上保存旧数据?

下拉Tailwind CSS菜单与怪异beviour

Redux工具包-useSelector如何通过Reducer引用InitialState?

如何使用useState响应快速/顺序状态更新

在Reaction中的第一次装载时,Use Effect返回空数组

Reaction路由-如何在布局路由内呈现&q;/:id&q;路由

如何更改TimePicker中下拉菜单的背景 colored颜色 和字体 colored颜色 - MUI React

为什么 useEffect 的初始化对于加载 localStorage 不起作用?

React-router-dom的链接不改变路由(ReactRouter6)

在一个事件处理程序中进行多次调度是个好主意吗?

如何在 React 过滤器中包含价格过滤器逻辑?

React - 将一个充满空值的无限大小的数组存储在 ref 中是否可以,或者我应该重置数组吗?

使用dayjs时如何在输入类型日期时间本地字段中设置默认值?

Material UI:使用 mui 手风琴时出现props 类型失败:isValidElement 不是函数

如何使用react 路由将 url 参数限制为一组特定的值?

React Router v6 - 访问嵌套路由和处理手写 url 的正确方法

如何在 Cypress E2E 的站点上测试react 组件?

无法重用我的组件,它只显示 1 次