Unable to simulate the navigator.language

I'm currently in the process of writing unit tests for some of my shared utility functions. As someone who is relatively new to unit testing, I am encountering difficulties when trying to mock certain global objects. Specifically, I am struggling to find a way to mock or update the value of navigator.language, as it always returns en-US. I have attempted to use Object.defineProperty and various Jest mock objects, but without success.

The interesting thing is that if I use console.log(navigator.language) within the test, the mocked value is displayed. However, the utility function does not seem to recognize this value.

Here is the code snippet:

//utils.js

export function getLang() {
  if (navigator.languages) return navigator.languages[0];
  return navigator.language;
}
//utils.spec.ts

describe('Navigator', () => {
  afterEach(() => {
    jest.restoreAllMocks();
  });


  //Error - Failing
  it('should return the exact language response if there is one', () => {
    jest.spyOn(navigator, 'language', 'get').mockImplementation(() => 'en-fr');
    expect(getLang()).toBe('en-fr');
  });



  // Successful - passing
  it('should return the first language if there is an array of languages', () => {
    jest
      .spyOn(navigator, 'languages', 'get')
      .mockImplementation(() => ['en-fr', 'en-US', 'en']);
    expect(getLang()).toBe('en-fr');
  });
});
    Expected: "en-fr"
    Received: "en-US"

      25 |     jest.spyOn(navigator, 'language', 'get').mockImplementation(() => 'en-fr');
      26 |     const lang = getLang();
    > 27 |     expect(lang).toBe('en-fr');
         |                  ^
      28 |   });
//package.json:

"jest": "^27.5.1",

Answer №1

To properly test your getLang function, you will need to create mocks for both the navigator.languages and navigator.language.

In this scenario, it is necessary to simulate navigator.languages returning either undefined or null in order to verify that the function correctly handles the case where

it("returns navigator.language when navigator.languages is undefined"

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

Ways to parse a JSON array using Javascript in order to retrieve a specific value if it is present

Below is the JSON code stored in an array: { "kind": "urlshortener#url", "id": "http://goo.gl/2FIrtF", "longUrl": "http://hike.com/?utm_source=facebook", "status": "OK", "created": "2015-09-22T13:45:53.645+00:00", "analytics": { "allTime": { ...

The argument with type 'void' cannot be assigned to a parameter with type 'Action'

Just getting started with Typescript and using VSCode. Encountering the following Error: *[ts] Argument of type 'void' is not assignable to parameter of type 'Action'. (parameter) action: void Here is the code snippet causing the err ...

My JavaScript code is being executed before Chrome Auto-fill

I have successfully created form input elements in Chrome that display a floating label when focused. However, I am encountering an issue when the browser autofills the username and password fields with yellow prefilled text. The JavaScript for the float ...

Having trouble drawing over buttons in HTML5 Canvas?

window.addEventListener("load", () => { const canvas = document.querySelector("#canvas"); const ctx = canvas.getContext("2d"); const color = document.querySelector("#color"); const strokeWeight = document.querySelector("#strokeWeight"); ...

Nativescript encountered an error due to an undefined variable called FIRAuth

I'm currently working on a project using Nativescript. While everything runs smoothly with Firebase on the local emulator, I encounter errors when testing the application on my iPhone. The specific error message is: CONSOLE LOG file:///app/vendor.js ...

Executing React Fetch API Twice upon loading the page

Double-fetching Issue with React Fetch API on Initial Page Load import React, { useState, useEffect } from 'react' import axios from 'axios'; import { Grid, Paper, TextField } from '@mui/material' import PersonOut ...

Encountering browser freezing issues with a Next.JS app when trying to add an input field

I am currently utilizing Next.JS to construct a form with two inputs. I have followed the traditional React approach for input text reading and validation. "use client" import { firebaseApp } from '@/app/firebase'; import React, { useCa ...

Endless re-renders induced by React-Table

While experimenting with a component that includes a table, I decided to give the react-table package a shot. The large component below is triggering endless calls to getRowModel. Additionally, there is a useEffect present to track re-renders unrelated to ...

Creating a distinctive vue form component from scratch

I have a requirement to develop a Vue component that enables users to create or edit a mailing address. The existing component structure is as follows: <template> <v-container> <v-form ref="form" lazy-validation> <v-text-field ...

Using NextJS getServerSideProps to Transfer Data to Page Component

Having trouble with my JavaScript/NextJS code, and not being an expert in these technologies. I'm using the method export const getServerSideProps: GetServerSideProps = async () => {} to fetch data from an integrated API within NextJS. The code mig ...

What is the best way to retrieve the scope of ng-repeat from another directive located on the same element as ng-repeat?

Is it possible to access a property from the ng-repeat scope in another directive within the same element as the ng-repeat directive? For instance, I would like to be able to use the child.class property in this scenario: <div ng-class="{{ child.class ...

How to utilize Vue.js method to retrieve child prop?

In my Vue.js project, I have created two components. The main component uses a child component called NoteRenderer, which includes a prop named data_exchange. My goal is to update this prop from the main component when a button is clicked. I attempted to a ...

JavaScript - Issue with retrieving object properties accurately

Here is a code snippet that I am working with: function retrieveObjects(name, data) { return data.filter(function(d) { return name.title == d.title; }).map(function(d) { return { "title": d.title, "sort": d. ...

Modify the data type of an object member based on its original type

I am seeking to convert the data type of each member in an object based on the specific member variable. Here is an example: class A { fct = (): string => 'blabla'; } class B { fct = (): number => 1; } class C { fct = (): { o ...

State in Next.js is still not prepared when the form is submitted

In my code, I have an onSubmit function that handles file uploads and creating records in a database. The issue I'm facing is that the record creation happens before the file upload process completes, resulting in incomplete data being stored. const ...

The precision of the css function in jQuery

Possible Duplicate: jQuery and setting margin using jQuery In the HTML snippet below, I have set margins for a paragraph element to center it: <p style="margin-left:auto; margin-right:auto; width:200px;">Hello</p> After that, I attempted ...

Debugging a node.js application remotely using SAP Cloud Foundry

Having successfully deployed multiple node.js express services on SAP Cloud Foundry, we have encountered a roadblock in the form of remote debugging. Recognizing that others may be facing similar challenges, we are putting forth a direct inquiry: What is ...

Issues arise when implementing Django templates in conjunction with jQuery

Here is an example of a Django template that I am working with: ... <div class="row"> <div class="col-lg-12"> <button type="submit" class="btn btn-primary" id="related"}>KIRK</button> </div> </div> . ...

AngularJS, sort through "afoo" excluding "foo"

I am attempting to implement a filter within an ng-repeat Main.HTML <table> <tr ng-repeat="param in MyParam | filter: UnrequestValue"> <td>{{param.Label}}</td> </tr> </table> Main.js MyParam: ...

Printing the result of an SQL query in Node.js without using braces

As a beginner in node.js with only a basic understanding of javascript, I apologize if I make any mistakes. I attempted to display the results retrieved by an SQL query in node.js using: <p>Users are " + util.inspect(results) + ".</p>" an ...