首页 > 解决方案 > mocha 单元测试 - 如何在每次测试后清除缓存的 javascript

问题描述

我正在尝试使用 mocha 和 jsdom 测试一个 javascript 文件(我们称之为 hello.js)。我有几个单元测试;每个测试基本上都会设置一些窗口属性,调用 hello.js,并检查窗口属性值。测试似乎以某种方式运行;但是,似乎 mocha 在第一次测试后使用了“缓存的”hello.js(日志记录仅在第一次测试中显示)。

有人能告诉我如何确保在每次测试中重新加载 hello.js 吗?

const expect = require('chai').expect;
const jsdom = require('jsdom');
const { JSDOM } = jsdom;
var dom = (new JSDOM(`<!DOCTYPE html><html><head></head><body></body></html>`));

describe('hello', ()=>{
    afterEach(()=>{
        dom = (new JSDOM(`<!DOCTYPE html><html><head></head><body></body></html>`));
        global.window = {};
        document = {};
        location = {};
    });
    it('should test A', ()=> {
        global.window = dom.window;
        global.window.document.cookie = "test=kiwi";
        document = global.window.document;
        const hello = require('../public/hello.js');
       expect(document.getElementsByTagName('IFRAME').length).to.equal(1);
    });
    it('should test B', ()=> {
        global.window = dom.window;
        global.window.document.cookie = "test=apple";
        document = global.window.document;
        const hello = require('../public/hello.js');
       expect(document.getElementsByTagName('IFRAME').length).to.equal(0);
    });
});

标签: javascriptunit-testingmocha.jsjsdom

解决方案


您可以使用一个库来为您执行此操作:

例子: const resetCache = require('resnap')(); // Capture "clean" cache state

参考:重拍


推荐阅读