我想了解在測試的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,所以我還不能使用胖箭頭。 –