我想了解在测试的NodeJS承诺,和测试,我已经在其他语言中使用的方法,在这里没有我有点。基本的问题是“我怎么有效地测试在一个或多个链接的,然后(和完成或挂钩)承诺块间接投入和产出?”测试中承诺的NodeJS
这里的lib/test.js
来源:
var Bluebird = require("bluebird"),
fs = Bluebird.promisifyAll(require("fs"));
function read(file) {
return fs.readFileAsync(file)
.then(JSON.parse)
.done(function() {
console.log("Read " + file);
});
}
function main() {
read("test.json");
}
if (require.main === module) {
main();
}
module.exports = read;
而这里的tests/test.js
var Bluebird = require("bluebird"),
chai = require("chai"),
expect = chai.expect,
sinon = require("sinon"),
sandbox = sinon.sandbox.create(),
proxyquire = require("proxyquire");
chai.use(require("chai-as-promised"));
chai.use(require("sinon-chai"));
describe("test", function() {
var stub, test;
beforeEach(function() {
stub = {
fs: {
readFile: sandbox.stub()
}
}
test = proxyquire("../lib/test", stub);
});
afterEach(function() {
sandbox.verifyAndRestore();
});
it("reads the file", function() {
test("test.json");
expect(stub.fs.readFile).to.have.been.calledWith("test.json");
});
it("parses the file as JSON", function() {
stub.fs.readFileAsync = sandbox.stub().returns(Bluebird.resolve("foo"));
sandbox.stub(JSON, "parse");
test("test.json");
expect(JSON.parse).to.have.been.calledWith("foo");
});
it("logs which file was read", function() {
stub.fs.readFileAsync = sandbox.stub();
sandbox.stub(JSON, "parse");
test("bar");
expect(console.log).to.have.been.calledWith("Read bar")
});
});
我意识到,这些例子是微乎其微的,做作的来源,但我希望尝试和理解如何测试承诺链,而不是如何读取文件并将其解析为JSON。 :)
另外,我没有绑定到任何框架或类似的东西,所以如果我在抓取任何包含的NodeJS库时无意中选择了糟糕的内容,那么也将赞赏召唤出来。
谢谢!
谢谢。我仍然使用NodeJS的v0.12.2,所以我还不能使用胖箭头。 –