我试图模拟呼叫一个服务,但我用以下信息挣扎: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将模拟定义移到了文件的顶部).
谁能解释一下我该怎么解决这个问题吗?我看到一些解决方案需要在模拟调用中引用,但我不明白如何使用类文件来实现这一点.