使用 Jest 模拟的服务会导致“不允许 jest.mock() 的模块工厂引用任何超出范围的变量”错误

2024-01-04

我正在尝试模拟对服务的调用,但我正在努力处理以下消息:模组厂jest.mock()不允许引用任何超出范围的变量.

我正在使用 babel 和 ES6 语法、笑话和酶。

我有一个简单的组件叫做Vocabulary它得到一个列表VocabularyEntry- 对象来自vocabularyService并渲染它。

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
    }
}

The vocabularyServise非常简单:

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

    });
});

运行测试会导致错误: Vocabulary.spec.js: babel-plugin-jest-hoist: The module factory ofjest.mock()不允许引用任何超出范围的变量。 无效的变量访问:VocabularyEntry。

据我了解,我无法使用 VocabularyEntry 因为它没有声明(因为开玩笑将模拟定义移动到文件顶部)。

谁能解释一下我该如何解决这个问题?我看到了需要模拟调用中的引用的解决方案,但我不明白如何使用类文件来做到这一点。


您需要将模拟组件存储在名称前缀为“mock”的变量中。 该解决方案基于我收到的错误消息末尾的注释。

注意:这是防止未初始化的模拟的预防措施 变量。如果保证mock是惰性需要的,则变量 名称前缀为mock是允许的。

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

const mockVocabulary = () => new VocabularyEntry("a", "a1");

jest.mock('../../../src/services/vocabularyService', () => ({
    default: mockVocabulary
}));

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

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

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

    // expect something

});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Jest 模拟的服务会导致“不允许 jest.mock() 的模块工厂引用任何超出范围的变量”错误 的相关文章

随机推荐