Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
    });
});
like image 388
coffeefirst Avatar asked Jan 27 '26 21:01

coffeefirst


1 Answers

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

like image 121
mwilson Avatar answered Jan 30 '26 10:01

mwilson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!