4 javascript asynchronous generator node.js
如何让Mocha等到异步函数完成?
var fs = require('mz/fs');
var co = require('co');
module.exports = new filecache();
function filecache () {
var self = this;
var storage = storage || {};
self.cache = co(function* (filePath, fileName) {
if (yield fs.exists(filePath)) {
storage[fileName] = yield fs.readFile(filePath);
}
});
self.has = function has (fileName) {
return storage.hasOwnProperty(fileName);
};
}
Run Code Online (Sandbox Code Playgroud)
var expect = require('chai').expect;
describe('phialcash', function () {
var filecache;
var filePath;
var fileName;
beforeEach(function () {
filecache = require('..');
filePath = './tests/file.fixture.txt';
fileName = filePath.split("/").pop();
});
describe('#exists', function () {
it('returns true if a file exists in the cache', function () {
filecache.cache(filePath, fileName);
expect(filecache.has(fileName)).to.equal(true);
});
});
});
Run Code Online (Sandbox Code Playgroud)
测试失败,因为filecache.cache(filePath, fileName);异步执行因此filecache.has(fileName)在运行期望时仍为false.
您应该co在方法调用的站点使用而不是在定义中使用.
self.cache = function* (filePath, fileName) {
if (yield fs.exists(filePath)) {
storage[fileName] = yield fs.readFile(filePath);
}
};
Run Code Online (Sandbox Code Playgroud)
测试时,将函数标记为异步并传递done给协同例程.co将done使用参数调用回调done(err, response).异步调用或失败的expect操作中抛出的任何异常都将导致测试用例失败.
describe('#exists', function () {
it('returns true if a file exists in the cache', function (done) {
co(function * () {
yield *filecache.cache(filePath, fileName); //generator delegation.
expect(filecache.has(fileName)).to.equal(true);
})(done);
});
});
Run Code Online (Sandbox Code Playgroud)
这是一个使用的应用程序的摘录koa,它在内部用于co处理控制流.编辑的所有语句都是yield返回的异步调用thunks.
group.remove = function * (ids) {
var c3Domain = this.c3Domain;
let deletedCount = yield this.baseRemove(ids);
if(deletedCount > 0) {
let deletedGroupMappings = yield [this.connection.query(UNMAP_GROUPS, [this.c3Id, ids]), this.tag.unmapGroupTags(ids)];
let deletedQueueCount = yield this.removeQueuesFromXml(ids);
if(deletedQueueCount > 0) {
let eslCommands = ['reloadxml'].concat(ids.map(function (id) {
return ['callcenter_config queue unload', id + '@' + c3Domain];
}));
yield this.esl.multiApi(eslCommands);
}
}
return deletedCount;
};
Run Code Online (Sandbox Code Playgroud)
测试用例:
it('should delete group', function (done) {
co(function *() {
let count = yield group.remove(['2000'])
assert(count === 1)
})(done)
})
Run Code Online (Sandbox Code Playgroud)