【发布时间】:2015-07-19 18:15:28
【问题描述】:
我正在尝试使用 Jest 测试我的 React 存储(我坚持使用 Flux 架构),但不确定何时需要模拟存储功能。为了说明我的观点,这是我的商店代码的一部分:
export default class AdminStore extends EventEmitter {
constructor() {
super();
this.users = [];
this.userTotal = 0;
this.profile = {};
AdminDispatcher.register((payload) => {
switch (payload.eventName) {
case AdminConstants.USER_TOTAL:
this.userTotal = payload.total;
this.emit('change');
break;
case AdminConstants.ALL_USERS:
this.users = payload.users;
this.emit('change');
break;
case AdminConstants.FETCH_USER:
this.profile = payload.profile;
this.emit('change');
break;
default:
break;
}
return true;
});
}
syncUsers() {
return this.users;
}
syncUserTotal() {
return this.userTotal;
}
syncProfile() {
return this.profile;
}
}
这是我的 Jest 测试代码的 sn-p:
jest.dontMock('../AdminStore.js');
jest.dontMock('../../constants/AdminConstants.js');
describe('AdminStore', () => {
let callback;
let AdminStore;
let AdminDispatcher;
let AdminConstants = require('../../constants/AdminConstants.js');
beforeEach(() => {
AdminStore = require('../AdminStore.js');
AdminDispatcher = require('../../dispatcher/AdminDispatcher.js');
callback = AdminDispatcher.register.mock.calls[0];
});
it ('should initialize with a user total of 0', () => {
let total = AdminStore.syncUserTotal();
expect(total).toEqual(0);
});
});
此测试的我的 Jest 输出如下所示:
● AdminStore › it should initialize with a user total of 0
- TypeError: undefined is not a function
at Spec.<anonymous> (/Users/seanchen/karma/admin-new/src/js/stores/__tests__/AdminStore-test.js:34:32)
at jasmine.Block.execute (/Users/seanchen/karma/admin-new/node_modules/jest-cli/vendor/jasmine/jasmine-1.3.0.js:1065:17)
at jasmine.Queue.next_ (/Users/seanchen/karma/admin-new/node_modules/jest-cli/vendor/jasmine/jasmine-1.3.0.js:2098:31)
at null._onTimeout (/Users/seanchen/karma/admin-new/node_modules/jest-cli/vendor/jasmine/jasmine-1.3.0.js:2088:18)
1 test failed, 1 test passed (2 total)
Run time: 3.493s
AdminStore.syncUserTotal() 需要被嘲笑吗?我真的不确定为什么它是未定义的。
【问题讨论】:
-
你能把代码贴在第 34 行左右吗?我们看不到行号
-
Jest 代码中的第 34 行是
let total = AdminStore.syncUserTotal();。
标签: unit-testing reactjs reactjs-flux jestjs