-1

I have a function that simply returns the 'lang' attribute from the document.documentElement as:

const getLang = () => document.documentElement.getAttribute('lang');

I need to write a test case for this. Right now I am doing a spy on/mock implementation of the function that simply returns a string as 'en':

import * as LangUtils from './langutils.ts';

test('returns the lang attribute', () => {
    const mock = jest.spyon(LangUtils, 'getLang');
    mock.mockImplementation(() => 'en');
    expect(c.getLang()).toEqual('en');
    mock.mockRestore();  
})

But I want to test it the right way. How do I mock the html document using JSDOM? I have tried to create a document element using JSDOM before the actual expect statement and then assigning a 'lang' attribute to it using Object.assign, however it doesn't work. My function in the expect block is able to find the document element but not the lang attribute. Console logging the document shows a location property that I don't understand. How do I make my function use the mock document instead of nodejs document? (PS: I have set the testenv to JSDOM in jest.config.)

Rutwick Gangurde
  • 4,772
  • 11
  • 53
  • 87

1 Answers1

0

I have found the solution. My Jest wasn't configured correctly, I did so by reinstalling jest-environment-jsdom. Now I can do this:

test('returns the lang attribute', () => {
    window.document.documentElement.setAttr('lang', 'en');
    expect(getLang()).toEqual('en');
})

Window correctly points to the JSDOM window object and hence document is able to return the lang attr.

Rutwick Gangurde
  • 4,772
  • 11
  • 53
  • 87