正如 Zbigniew 所建议的那样,Future.of
并且Future.reject
是使用普通的旧 javascript 或您喜欢的任何工具或框架进行模拟的绝佳候选者。
要回答您问题的第 2 部分,关于如何使用 Fluture 进行 TDD 的任何具体建议。当然,它不应该是一种真正的方式。但是,如果您计划在整个应用程序中使用 Futures,我确实建议您花一点时间在可读性和编写测试的易用性上。
这适用于您经常包含在测试中的任何内容,而不仅仅是 Futures。这个想法是,当您浏览测试用例时,您会看到开发人员的意图,而不是样板文件来让您的测试完成您需要的工作。
就我而言,我使用 BDD 风格的 mocha & chai(当时给出)。为了便于阅读,我创建了这些辅助函数。
const {expect} = require('chai');
exports.expectRejection = (f, onReject) =>
f.fork(
onReject,
value => expect.fail(
`Expected Future to reject, but was ` +
`resolved with value: ${value}`
)
);
exports.expectResolve = (f, onResolve) =>
f.fork(
error => expect.fail(
`Expected Future to resolve, but was ` +
`rejected with value: ${error}`
),
onResolve
);
正如你所看到的,没有什么神奇的事情发生,我只是让意想不到的结果失败,让你处理预期的路径,用它做更多的断言。
现在一些测试看起来像这样:
const Future = require('fluture');
const {expect} = require('chai');
const {expectRejection, expectResolve} = require('../util/futures');
describe('Resolving function', () => {
it('should resolve with the given value', done => {
// Given
const value = 42;
// When
const f = Future.of(value);
// Then
expectResolve(f, out => {
expect(out).to.equal(value);
done();
});
});
});
describe('Rejecting function', () => {
it('should reject with the given value', done => {
// Given
const value = 666;
// When
const f = Future.of(value);
// Then
expectRejection(f, out => {
expect(out).to.equal(value);
done();
});
});
});
跑步应该是一次通过,一次失败。
✓ Resolving function should resolve with the given value: 1ms
1) Rejecting function should reject with the given value
1 passing (6ms)
1 failing
1) Rejecting function
should reject with the given value:
AssertionError: Expected Future to reject, but was resolved with value: 666
请记住,这应该被视为异步代码。这就是为什么我总是接受该done
函数作为参数it()
并在预期结果结束时调用它。或者,您可以更改辅助函数以返回一个承诺并让 mocha 处理它。