I am currently attempting to manipulate the documentElement lang property for my testing purposes, but I am struggling to find a solution. I have tried defining setupFiles in Jest config, which allowed me to define it but did not give me the option to change it for different tests. This issue is discussed in more detail here: Mocking `document` in jest
A snippet of the testing code in question is as follows:
const lang: string = document.documentElement.lang ?
document.documentElement.lang : Constraints.DEFAULT_LANGUAGE;
The test case is structured like this:
test('should pass `en` language when document hasn't specified any', () => {
const spy = jest.spyOn(window.document, 'documentElement', 'get');
expect(spy).toHaveBeenCalled();
});
When utilizing setupFiles as shown below:
Object.defineProperty(document, 'documentElement', {
writable: true,
configurable: true,
value: document.createElement('document')
});
I encounter an error message stating:
Property documentElement does not have access type get
However, if I attempt to spy on it without the setupfile.js
configured, the spy is never triggered.
EDIT
Here is a clearer example of what I am aiming to achieve:
const lang: string = document.documentElement.lang ?
document.documentElement.lang : Constraints.DEFAULT_LANGUAGE;
component.src = `/${lang}/mysite`;
test('should pass `de` language when document has one specified', () => {
const spy = jest.spyOn(window.document, 'documentElement', 'get');
const mockElement = document.createElement('document');
mockElement.lang = 'de';
spy.mockReturnValue(mockElement);
expect(component.src).toContain('/de/');
});
During the test, I receive the following message:
expect(received).toContain(expected) // indexOf
Expected substring: "/de/"
Received string: "http://localhost/en/mysite"