我正在试验Jest来单元测试一个角度的应用程序。为了测试角度绑定,我尝试使用jsdom (N.B。我使用v3.1.2,因为我使用的是节点而不是IO)。当我需要用html加载脚本时,测试似乎是在加载脚本之前完成的。
我已经将我的测试用例简化为使用来自jsdom的示例:
it('updates the view without error', function(){
var jsdom = require('../../../../node_modules/jsdom/lib/jsdom');
jsdom.env(
'<p><a class="the-link" href="https://github.com/tmpvar/jsdom">jsdom!</a></p>',
["http://code.jquery.com/jquery.js"],
function (errors, window) {
//console.log("contents of a.the-link:", window.$("a.the-link").text());
console.log("Completed");
expect(errors).toBeNull();
}
);
console.log('exiting...');
});如果我运行这个测试,测试将通过,但是“已完成的”日志消息将不会被打印出来,我也可以用一些明显失败的东西替换expect,比如expect(false).toBeTruthy(),并且测试仍然会“通过”。如果我删除了jquery的注入,那么所有这些都可以正常工作。
在退出测试之前,如何确保加载了脚本?更广泛地说,在Jest中显式地使用jsdom感觉有点不对。有更好的办法吗?
发布于 2015-03-02 14:52:44
发布于 2018-06-25 16:24:59
我认为测试异步代码的最好方法是通过“完成”回调,正如文档中所解释的那样。然后,您的代码将变成:
it('updates the view without error', function(done){
var jsdom = require('../../../../node_modules/jsdom/lib/jsdom');
jsdom.env(
'<p><a class="the-link" href="https://github.com/tmpvar/jsdom">jsdom!</a></p>',
["http://code.jquery.com/jquery.js"],
function (errors, window) {
//console.log("contents of a.the-link:", window.$("a.the-link").text());
console.log("Completed");
expect(errors).toBeNull();
done();
}
);
console.log('exiting...');
});
https://stackoverflow.com/questions/28812307
复制相似问题