coffeefirst
coffeefirst

Reputation: 135

mocha unit test - how to clear cached javascript after each test

I'm trying to test a javascript file (let's call it hello.js) using mocha and jsdom. I have several unit tests; each test basically sets up some window properties, calls hello.js, and checks window property values. Tests seem to be running somehow; however, it seems like mocha uses "cached" hello.js after the first test (logging only shows in the first test).

Can someone tell me how I can ensure that I reload hello.js in each test?

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);
    });
});

Upvotes: 3

Views: 6907

Answers (2)

Muhammed Moussa
Muhammed Moussa

Reputation: 5195

you can use flush-cache

npm i flush-cache --save-dev
beforeEach(function () {
  flush() 
})

Upvotes: 0

mwilson
mwilson

Reputation: 12910

There's a library that you can pull in to do this for you:

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

Reference: Resnap

Upvotes: 1

Related Questions