我对摩卡测试有个奇怪的问题。我不理解对异步和承诺函数的深刻理解。
我有跟踪测试
mytest.js
describe(" store tests", () => {
jsonfile.readFile(testDateFile).then(data => {
describe("store is running", function() {
it(`should show home page ${data}`, async function() {
console.log("working");
});
});
});
});
哪里
jsonfile.readFile
回报承诺。
当我用
./node_modules/.bin/mocha test/verify-urls.js
,它永远不会进入“it”。
但是当我再加上下面的描述
describe(" store tests", () => {
describe("store is running", function() {
it("should do nothing", () => {});
});
jsonfile.readFile(testDateFile).then(data => {
describe("store is running", function() {
it(`should show home page ${data}`, async function() {
console.log("working");
});
});
});
});
然后
it(should show home page ${data}
执行。
如有任何关于理解这一问题的建议,将不胜感激。
编辑:
我想出来了。问题出在
jsonfile.readFile(testDateFile)
。因为jsonfile.readfile是异步的和不同的线程。摩卡测试运行将在当前线程,并不会等待返回的承诺。
我只是将readfile方法移到测试之外,并在执行descripe之前加载。