如何 运行 qunit assertions on resolving Promise
How to run qunit assertions on resolving a Promise
我正在为 returns 承诺的函数编写测试,并且无法 运行 断言解决或拒绝承诺。我不能在这个项目上使用 ES6,所以我使用的是 rsvp.js 库,它声称实现了 Promises/A+ 规范。我使用的是最新的 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;
});
失败 "Expected 1 assertions, but 0 were run"
失败测试:
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;
});
失败 "Promise rejected during get promise when loading empty groups: No groups were loaded"
承诺通过链接工作。 Promises 是对值的不可变包装器。
当你这样做时:
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);
});
});
我正在为 returns 承诺的函数编写测试,并且无法 运行 断言解决或拒绝承诺。我不能在这个项目上使用 ES6,所以我使用的是 rsvp.js 库,它声称实现了 Promises/A+ 规范。我使用的是最新的 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;
});
失败 "Expected 1 assertions, but 0 were run"
失败测试:
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;
});
失败 "Promise rejected during get promise when loading empty groups: No groups were loaded"
承诺通过链接工作。 Promises 是对值的不可变包装器。
当你这样做时:
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);
});
});