最佳答案
我试图模仿一个服务呼叫,但我挣扎与以下信息: jest.mock()
的模块工厂不允许引用任何范围外的变量。
我用的是 Babel 和 ES6语法,玩笑和酶。
我有一个名为 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
});
});
运行测试会导致一个错误: babel-plugin-jest-hoist: jest.mock()
的模块工厂不允许引用任何范围外的变量。
无效的变量访问: 词汇表条目。
据我所知,我不能使用词汇表条目,因为它没有声明(jest 将模拟定义移动到文件的顶部)。
有人能解释一下我该怎么补救吗?我看到了需要在模拟调用中引用的解决方案,但我不明白如何使用类文件实现这一点。