每次测试后如何让业力清除dom?

Sup*_*per 2 karma-runner

我正在测试的组件在 it() 测试中对 dom 进行了一些更改,但是它在下一个 it() 测试中仍然存在,这破坏了我的测试。有没有办法在每个 it() 测试中重置 DOM?

Jan*_*ser 8

对于没有 JQUERY 用户:

afterEach(function () {
    document.body.innerHTML = '';
});
Run Code Online (Sandbox Code Playgroud)

你也可以使用beforeEach,但我喜欢把它想象成一张餐桌,你开始之前不清理,你自己清理之后

我写了一个小 DomCleaner,它在你的测试期间跟踪事件,并在清理时清理主体(requireJS,但你可以根据需要更改代码):

define(function () {
    'use strict';

    var installed = false,
        documentAddListener,
        documentListeners,
        windowAddListener,
        windowListeners;
    return {
        install: function () {
            if (installed) {
                throw new Error('Trying to install document cleaner, but its already installed!');
            }
            installed = true;
            documentAddListener = document.addEventListener;
            windowAddListener = window.addEventListener;
            spyOn(document, 'addEventListener');
            spyOn(window, 'addEventListener');
            documentListeners = [];
            windowListeners = [];
            document.addEventListener.and.callFake(function () {
                documentListeners.push(arguments);
                documentAddListener.apply(null, arguments);
            });
            window.addEventListener.and.callFake(function () {
                documentListeners.push(arguments);
                windowAddListener.apply(null, arguments);
            });
        },
        cleanup: function () {
            if (!installed) {
                throw new Error('Trying to cleanup document, but cleaner is not installed!');
            }
            installed = false;
            documentListeners.forEach(function (listener) {
                document.removeEventListener.apply(null, listener);
            });
            windowListeners.forEach(function (listener) {
                window.removeEventListener.apply(null, listener);
            });
            documentListeners = [];
            windowListeners = [];
            document.body.innerHTML = '';
        },
    };
});
Run Code Online (Sandbox Code Playgroud)

像这样使用它(在你的第一次描述中):

beforeEach(function () {
   domCleaner.install();
});
afterEach(function () {
   domCleaner.cleanup();
});
Run Code Online (Sandbox Code Playgroud)