使用 jsdom 和 Jest

And*_*nes 2 javascript jsdom angularjs jestjs

我正在尝试使用 Jest 对角度应用程序进行单元测试。为了测试角度绑定,我尝试使用 jsdom (注意,我使用 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...');
});
Run Code Online (Sandbox Code Playgroud)

如果我运行此测试,测试将通过,但不会打印“已完成”日志消息,我还可以用明显失败的内容替换期望,例如expect(false).toBeTruthy(),并且测试仍将“经过”。如果我删除 jquery 的注入,那么一切都会按预期工作。

我应该如何确保在退出测试之前加载脚本?更一般地说,在 Jest 中显式使用 jsdom 感觉有点不对劲。有没有更好的办法?

Fel*_*ing 5

因为.env可能是异步的,所以在调用回调之前测试将始终存在。

根据jest 教程,您可以简单地将 HTML 分配给document.body.innerHTML

// Set up our document body
document.body.innerHTML =
    '<div>' +
    ' <span id="username" />' +
    ' <button id="button" />' +
    '</div>';
var $ = require('jquery');
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用pit代替it并从函数中返回一个承诺。

  • 谢谢。很高兴有 RTFM 的礼貌版本:) (2认同)