我有一个React视图,它与商店通信。我已经成功地分别测试了视图和存储,但没有结合起来。
我跟踪了这里记录的结构,但收到了TypeError。看起来Jest正在尝试将商店注册为一个组件,即使我使用了dontMock。
Using Jest CLI v0.2.0
PASS __tests__/unit/spec/stores/ViewStore-spec.js (0.248s)
FAIL __tests__/unit/spec/components/View-spec.react.js (0.942s)
undefined
● View › it defaults to zero unread
- TypeError: /Users/matnorri/dev/projects/matnorri/web-client/src/app/scripts/components/View.react.js: /Users/matnorri/dev/projects/matnorri/web-client/src/app/scripts/stores/ViewStore.js: Cannot call method 'register' of undefined
at /Users/matnorri/dev/projects/matnorri/web-client/src/app/scripts/stores/ViewStore.js:43:31
at Object.runContentWithLocalBindings (/Users/matnorri/dev/projects/matnorri/web-client/node_modules/jest-cli/src/lib/utils.js:357:17)
...我已经包含了下面的相关代码,但如果有必要,可以提供完整的代码。
视图Jest测试
jest.dontMock('../../../../src/app/scripts/components/View.react');
jest.dontMock('../../../../src/app/scripts/stores/ViewStore');
describe('View', function() {
var React;
var TestUtils;
var ViewComponent;
var View;
beforeEach(function() {
React = require('react/addons');
TestUtils = React.addons.TestUtils;
ViewComponent =
// Tried both lines with same effect.
// require('../../../../src/app/scripts/components/View.react.js');
require('../../../../src/app/scripts/components/View.react');
View = TestUtils.renderIntoDocument(<ViewComponent />);
});
it('defaults to zero unread', function() {
View._toString = jest.genMockFunction();
View._onChange();
expect(View.state.unread).toBe(0);
});
});谢谢!
发布于 2014-12-11 21:25:32
回答你的问题
我也遇到了这个问题,而不是嘲笑对象-分配解决了我的问题。将jest.dontMock('object-assign');添加到规范文件中。这将解决问题。
// View Jest test
jest.dontMock('../../../../src/app/scripts/components/View.react');
jest.dontMock('../../../../src/app/scripts/stores/ViewStore');模拟还是不模拟
有关何时“模拟或不模拟”的更多信息可以在Jest文档网站上找到。
Jest修改" require“方法的默认行为,并实现它自己的require方法。这样,它们就能够模拟文件中的每个函数。因此,如果您想要某些东西真正工作(比如与一个商店),您不应该嘲笑该文件。
在您的例子中,您不是在模拟ViewStore,所以这个商店中的每个函数都将被调用。因为您没有模拟object-assign,所以对象赋值函数无法工作。这样,ViewStore就不会以正确的方式创建(它返回undefined),并且测试抛出错误Cannot call method 'register' of undefined,因为assign函数没有工作,因为它被模拟了。
同样,如果您阅读Jest网站上的文档,您将发现关于何时“模拟或不模拟”的详细描述。
附加信息
我建议在测试配置中将“对象分配”和其他常用模块(如送交/下划线)添加到unmockedModulePathPatterns中。有关此问题的更多信息:https://facebook.github.io/jest/docs/api.html#config-unmockedmodulepathpatterns-array-string
https://stackoverflow.com/questions/27323640
复制相似问题