我正在为一个返回promise的函数编写测试,并且无法在解析或拒绝promise时运行断言。我不能在这个项目上使用ES6所以我使用的是声称实现Promises / A +规范的rsvp.js库。我正在使用最新的qunit版本1.17.1
被测功能:
var loadGroups = function(data) {
return new RSVP.Promise(function(resolve, reject) {
var groups = [];
// ... some code to populate the groups array
if(groups.length > 0) {
resolve(groups);
} else {
reject("No groups were loaded");
}
});
};
成功测试:
test('success test', function(assert) {
assert.expect(1);
var promise = loadGroups(testData);
promise.then(function(groups) {
assert.deepEquals(groups.length, 1);
});
return promise;
});
这与"预期的1个断言失败,但是0运行"
失败测试:
test('failure test', function(assert) {
assert.expect(1);
var promise = loadGroups([]);
promise.then(null, function(message) {
assert.equals(message, "No groups were loaded");
});
return promise;
});
在加载空组时,在失败期间拒绝承诺失败:没有加载任何组"
答案 0 :(得分:10)
当你这样做时:
promise.then(function(e){
// do something
});
您不会更改promise
您正在创建新承诺。相反,你需要将承诺链接起来:
test('success test', function(assert) {
assert.expect(1);
var promise = loadGroups(testData);
// return the `then` and not the original promise.
return promise.then(function(groups) {
assert.deepEquals(groups.length, 1);
});
});