vendredi 23 octobre 2020

Global variable added to window in Jest test

I am seeing some weird behavior in a Jest test. When I use width = 600 below, the test passes but when I use var width = 600 instead it fails with the this.width being undefined. Both work in a real browser. Why do they behave differently? Shouldn't the var width = 600 work?

The working test is just below and the not working one is below that.

/**
 * @jest-environment jsdom
 */

let spy;

width = 600;
var shape = {width: 300};

var showWidth = function()
{
    document.write(this.width);
}

describe('checkSomeScopeStuff', function () {

     it('check2', () => {
     spy = jest.spyOn(document, 'write');

     showWidth();

     expect(spy.mock.calls.length).toBe(1);
     expect(spy).toHaveBeenCalledWith(600);
    });
});

The test that fails is:

/**
 * @jest-environment jsdom
 */

let spy;

var width = 600;
var shape = {width: 300};

var showWidth = function()
{
    document.write(this.width);
}

describe('checkSomeScopeStuff', function () {

     it('check2', () => {
     spy = jest.spyOn(document, 'write');

     showWidth();

     expect(spy.mock.calls.length).toBe(1);
     expect(spy).toHaveBeenCalledWith(600);
    });
});

Aucun commentaire:

Enregistrer un commentaire