【发布时间】:2017-11-22 19:11:13
【问题描述】:
我正在尝试模拟对服务的调用,但遇到以下消息:jest.mock() 的模块工厂不允许引用任何范围外的变量 .
我正在使用带有 ES6 语法、玩笑和酶的 babel。
我有一个名为Vocabulary 的简单组件,它从vocabularyService 获取VocabularyEntry-Objects 列表并呈现它。
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
}
}
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 of jest.mock() is not allowed to reference any out-of-scope variables。
无效的变量访问:VocabularyEntry。
据我了解,我不能使用 VocabularyEntry,因为它没有声明(因为 jest 将模拟定义移动到文件顶部)。
谁能解释我如何解决这个问题?我看到了需要在模拟调用中引用的解决方案,但我不明白如何使用类文件来做到这一点。
【问题讨论】:
标签: unit-testing reactjs babeljs jestjs