在针对动作创建者编写Mocha测试规范时,如果在动作创建者中生成时间戳,我如何确定时间戳是什么?
它不必使用Sinon,但我试图利用Sinon Fake Timers来"冻结时间"而且由于我对顽固和嘲弄的有限知识,似乎无法将这些拼凑在一起。如果这被认为是一个Redux反模式,请指向一个更好的方向,但我的理解是Redux动作创建者可以是非纯函数,与reducer不同。
从我Redux Writing Tests Recipes借一点点是我理解的问题的核心......
CommonUtils.js
import { getTimestamp } from '../../utils/CommonUtils';
export function addTodo(text) {
return {
type: 'ADD_TODO',
text,
timestamp: getTimestamp() // <-- This is the new property
};
};
TodoActions.js
import expect from 'expect';
import * as actions from '../../actions/TodoActions';
import * as types from '../../constants/ActionTypes';
import { getTimestamp } from '../../utils/CommonUtils';
describe('actions', () => {
it('should create an action to add a todo', () => {
const text = 'Finish docs';
const timestamp = getTimestamp(); // <-- This will often be off by a few milliseconds
const expectedAction = {
type: types.ADD_TODO,
text,
timestamp
};
expect(actions.addTodo(text)).toEqual(expectedAction);
});
});
TodoActions.spec.js
min
答案 0 :(得分:3)
测试时间我过去成功使用过此库:https://www.npmjs.com/package/timekeeper
然后在beforeEach和afterEach中,您可以将时间保存为特定的内容,然后让您的断言重置正常的时间。
let time;
beforeEach(() => {
time = new Date(1451935054510); // 1/4/16
tk.freeze(time);
});
afterEach(() => {
tk.reset();
});
现在您可以对返回的时间进行断言。这有意义吗?
答案 1 :(得分:0)
我仍然希望看到其他答案,但我终于得到了一个合理的解决方案。当 TodoActions 使用时,此答案使用proxyquire覆盖/替换 CommonUtils 中定义的 getTimestamp()方法。测试
不从上面修改 CommonUtils.js 或 TodoActions.js :
<强> TodoActions.spec.js 强>
import expect from 'expect';
import proxyquire from 'proxyquire';
import * as types from '../../constants/ActionTypes';
const now = '2016-01-06T15:30:00-05:00';
const commonStub = {'getTimestamp': () => now};
const actions = proxyquire('../../actions/TodoActions', {
'../../utils/CommonUtils': commonStub
});
describe('actions', () => {
it('should create an action to add a todo', () => {
const text = 'Finish docs';
const timestamp = now; // <-- Use the variable defined above
const expectedAction = {
type: types.ADD_TODO,
text,
timestamp
};
expect(actions.addTodo(text)).toEqual(expectedAction);
});
});