我正在为我编写的函数编写一些测试:当前代码按我预期的方式工作,但现在我需要 DRY 我的代码并进行重构。 下面你会看到我写的单元测试:
QUnit.test('Localized Date in Honolulu', assert => {
const stub = sinon.stub(constantDate, 'getTimezoneOffset', () => {
return '600';
});
console.log('timeSet', timeSet());
assert.strictEqual(timeSet(), '2017-07-29T14:00:00.000Z', 'there needs to be a message here');
stub.restore();
});
QUnit.test('San Francisco Date and Time', assert => {
const stub = sinon.stub(constantDate, 'getTimezoneOffset', () => {
return '420';
});
assert.strictEqual(timeSet(), '2017-07-29T17:00:00.000Z');
stub.restore();
});
QUnit.test('Sydney time', assert => {
const stub = sinon.stub(constantDate, 'getTimezoneOffset', () => {
return '-600';
});
assert.strictEqual(timeSet(), '2017-07-30T10:00:00.000Z', 'Expected the time in Sydney to be 10AM');
stub.restore();
});
尽管在我看来我应该能够重构 stub ,但我发现它具有挑战性,因为每个 stub 每次都有不同的返回值。我可以就如何使我的代码干净和干燥获得一些建议吗?
最佳答案
一个建议是使用偏函数。如您所知,sinon.stub
中的前两个参数对于每个单元测试都是相同的。因此,在执行单元测试之前,我们可以创建一个函数
const timezoneOffsetStub = (callback) => {
return sinon.stub(constantDate, 'getTimezoneOffset', callback);
}
(假设 constantDate
是全局定义的变量)
所以现在要在每个单元测试中 stub ,我们只需要定义不同的回调是什么。
QUnit.test('Localized Date in Honolulu', assert => {
const stub = timezoneOffsetStub(() => '600');
...
});
QUnit.test('San Francisco Date and Time', assert => {
const stub = timezoneOffsetStub(() => '420');
...
});
关于javascript - 重构一些有很多重复代码的单元测试。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45316571/