我正在创建一个元素(一个路由器 - 但这并不重要),它在附加特定的其他自定义元素后立即扫描 DOM。在某些情况下它需要抛出错误,我想测试这些。
我构建的测试没有失败 - 但据我所知,在附加我的元素之前测试已经失败。我怀疑这是事物的异步本质。
这是相关测试的片段。有问题的测试装置包含一些元素,这些元素会在“dom-change”事件发生(它有一个监听器)后导致其中一个元素失败,然后它会扫描 dom 中的其他内容。
it('should fail if two route elements both designate thenselves as home', function(done) {
var t= document.getElementById('multiple_home');
function multiple () {
t.create();
}
expect(multiple).to.throw(Error);
t.restore();
done();
});
我认为问题与以下事实有关:夹具是多次创建的,但在多次退出时尚未失败。我想知道我是否可以传递一个 Promise 来期待 - 但我不知道如何将多个变成一个 Promise 来尝试一下。
最佳答案
我最终找到了一种方法,但它需要对元素进行一些检测来支持这一点。
在元素“created”回调中,我创建一个 Promise 并将两个函数存储在“this”变量中来解析和拒绝它 - 因此:-
this.statusPromise = new Promise(function(resolve,reject){
this.statusResolver = resolve;
this.statusRejector = reject;
}.bind(this));
在 DOM 解析部分,我使用这样的 try catch block
try {
//parse the dom throwing errors if anything bad happens
this.statusResolver('Any useful value I like');
} catch (error) {
this.statusRejector(error);
}
然后我创建了一个返回 promise 的函数
domOK: function() {
return this.statusPromise;
}
最后,在我的测试中,我现在能够测试这样的东西(我在每个测试中加载固定装置,而不是 beforeEach,因为我为每个测试使用不同的固定装置。我确实在 afterEach 中再次清除它)。请注意 Promise 中 .then 和 .catch 函数的使用。
it('should fail if two route elements declare the same path name',function(done){
t = document.getElementById('multiple_path');
t.create();
r = document.getElementById('router')
r.domOK().then(function(status){
//We should not get here throw an error
assert.fail('Did not error - status is: ' + status);
done();
}).catch(function(error){
expect(error.message).to.equal('There are two nodes with the same name: /user');
done();
});
关于polymer - 如何测试连接时应该失败的 polymer 元件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33690007/