Simulation of documentElement language property in Jest

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"

Answer №1

Almost there! But, keep in mind that accessing the document.documentElement.lang property triggers the get accessor. To handle this, define the object as shown below:

Object.defineProperty(document, 'documentElement', {
    configurable: true,
    get () {
        return document.createElement('document');
    },
});

In your test, make sure to add the following line before the expect statement to trigger the getter and ensure the spy is called:

window.document.documentElement.lang;

EDIT

It's best to simplify your setup code and avoid using a spy. Instead, create a method to set the language in your constant. Then, test this method rather than the get action of documentElement.

Before calling your method, use the code below to set the lang property (imagine you have a language method):

test('should return `de` language when document has one specified', () => {
    Object.defineProperty(document.documentElement, 'lang', { value: 'de', configurable: true });

    expect(component.language()).toBe('de');
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process of comparing one regular expression against another in JavaScript?

I'm looking to check for matches between two regular expressions. To achieve this, I use the .test method on each one. If either of them returns true, I consider them a match. const regexify = (str) => new RegExp( '^' + str ...

Monitoring individual elements of an array within an Angular service

Is there a way to monitor changes in an array element within a service? Let's consider the following scenario with CartController and ProductListService. Within the ProductListService, data is fetched as follows: /** * Fetch all the products in us ...

Function "Contains" not Present in Object

Upon executing the code provided below, I encounter the following error message. An issue has arisen: Cannot find function contains in object Is Patient Fasting?/# of Hours->Yes; 12 hours. Here is the snippet of my code: var i = 0; var tempF ...

Encountering SUID Sandbox Helper Issue When Running "npm start" on WSL with Electron and Typescript

Can anyone help me with this issue? I have Node v8.10.0 and I'm attempting to follow a beginner tutorial on Electron + Typescript which can be found at the following link: https://github.com/electron/electron-quick-start-typescript Here is the full e ...

Resolving Undefined Vue Props Issue (handling props from Laravel blade)

I'm struggling to parse props from Laravel blade to a Vue component. Normally, this process works fine for me, but this time I am facing issues and it's not working at all. web.php Route::get('/catalog/{product_category_name}', functio ...

The issue arises when Node.js fails to identify the input fields that were dynamically inserted into the form

I came across a question similar to mine, but I found it challenging to apply the solution to node js. In my project, users can add items to a cart by clicking on them, which are then dynamically added to a form using jquery. However, upon submission, only ...

Leveraging CSS attribute selectors within JSX using TypeScript

With pure HTML/CSS, I can achieve the following: <div color="red"> red </div> <div color="yellow"> yellow </div> div[color="red"] { color: red; } div[color="yellow"] { color: yellow; ...

Task that merges multiple JSON files into one using Gulp

Within my directory, I have a collection of JSON files that contain arrays of objects. Folder A file1.json file2.json file3.json All the files in this folder have the same structure (a single array containing multiple objects). My goal is to execu ...

"Enhance your HTML table by selecting and copying cell values with a simple click and CTRL +

I stumbled upon a fantastic script for highlighting HTML table rows and it's working perfectly: I decided to modify the onclick event to onmouseover and included additional code to select a cell by clicking on it. Now I can select, check which one is ...

Develop a personalized event using JavaScript and activate it

I have encountered a problem with a Google ad that expands on click and closes when the close button is hit. However, due to changing conditions, I now need it to expand first and then automatically close after a certain time. Additionally, every time it e ...

Is there a way to seamlessly transfer (optional) parameters from a CloudFormation template to a CDK resource within a CfnInclude without statically defining the list of parameters?

Trying to grasp these syntax rules, unsure if it's possible. We have numerous CloudFormation templates that we want to deploy using CDK by constructing them with CfnInclude. The issue is that CfnInclude always needs an explicit parameters argument if ...

Learn the technique of hovering over an image to see it blur and reveal overlay text

Currently, I am in the process of creating my portfolio website and after experimenting with some code, I was able to achieve the desired outcome. <div id="nytimes" class="portfolio-thumbnail" style="left: 100px; top: 80px;"> <span class="text ...

Click on the print icon in the modal window

I have been working on a receipt generator for a client. The client can add payment receipts using the "Add" button, and upon submission, they have the option to convert it to PDF or print it. However, there seems to be an issue with printing as the text f ...

utilizing mongoose populate for displaying the author

One of the features on my website allows users to add notices, and I want the page to display the author of each notice. const notices = await Notice.findById(id).populate('author'); When I access this route, I can successfully log the authors o ...

What is the correct location for storing .html, .css, and other files in a project involving Typescript, Angular 2, and ASP.Net Core 1.0?

When following a Typescript tutorial to create an ASP.Net Core application (with or without Angular 2), it is recommended to set up a folder called Scripts and use gulp tasks to selectively copy only the .js files to the wwwroot folder during the build pro ...

Storing blank information into a Mongodb database with Node.js and HTML

Can someone please assist me with solving this problem? const express=require("express"); const app=express(); const bodyparser=require("body-parser"); const cors=require("cors"); const mongoose=require("mongoose"); ...

What is the process of triggering an action from within getInitialProps?

I've been struggling to integrate Redux into a Next.js app, particularly when trying to use the dispatch function within getInitialProps. For some reason, the store keeps returning as undefined and I can't seem to pinpoint the issue. I've fo ...

Guidelines for transferring data when a button is held down or pressed

I am looking to continuously send values while a button is pressed. Currently, a value is only sent with each click. Below is the current code: my_custom_script.js $(document).ready(function() { $('#left').mousedown(function() { var left ...

What could be causing the removeChild() method to fail when trying to delete a list item in JavaScript DOM manipulation?

Check out this interactive shopping list. You can add items, delete them, and mark them as completed. Adding and deleting items works fine, but there's an issue when toggling them. Issue (occurs when toggling multiple list items) If you add 3 items ...

What is the best method for initializing a grid combo box value using JavaScript?

How do I set the value of a combobox in a grid itemtemplate using JavaScript? <telerik:GridTemplateColumn AutoPostBackOnFilter="true" CurrentFilterFunction="Contains" DataField="FAULT" FilterControlWidth="100%" ...