"Sorry, but window.print function is not available in this environment

Whenever I try to execute something in jest, I keep encountering the same error message:

 console.error node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/virtual-console.js:29
    Error: Not implemented: window.alert
        at module.exports (D:\Docs\Projects\EMM\emm_next\node_modules\jest-environment-jsdom\node_modules\jsdom\lib\jsdom\browser\not-implemented.js:9:17)
        at D:\Docs\Projects\EMM\emm_next\node_modules\jest-environment-jsdom\node_modules\jsdom\lib\jsdom\browser\Window.js:594:7
        at util_ajvSchemaValidator (D:\Docs\Projects\EMM\emm_next\src\utils\commonUtility.ts:1557:5)
        at Object.<anonymous> (D:\Docs\Projects\EMM\emm_next\tests\unit\utils\commonUtility.test.ts:78:30)
        at Object.asyncJestTest (D:\Docs\Projects\EMM\emm_next\node_modules\jest-jasmine2\build\jasmine_async.js:108:37)
        at D:\Docs\Projects\EMM\emm_next\node_modules\jest-jasmine2\build\queue_runner.js:56:12
        at new Promise (<anonymous>)
        at mapper (D:\Docs\Projects\EMM\emm_next\node_modules\jest-jasmine2\build\queue_runner.js:43:19)
        at D:\Docs\Projects\EMM\emm_next\node_modules\jest-jasmine2\build\queue_runner.js:87:41
        at processTicksAndRejections (internal/process/task_queues.js:94:5) undefined

  console.error node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/virtual-console.js:29
    Error: Not implemented: window.print
        at module.exports (D:\Docs\Projects\EMM\emm_next\node_modules\jest-environment-jsdom\node_modules\jsdom\lib\jsdom\browser\not-implemented.js:9:17)
        at D:\Docs\Projects\EMM\emm_next\node_modules\jest-environment-jsdom\node_modules\jsdom\lib\jsdom\browser\Window.js:594:7
        at Object.<anonymous> (D:\Docs\Projects\EMM\emm_next\tests\unit\utils\commonUtility.test.ts:127:5)
        at Object.asyncJestTest (D:\Docs\Projects\EMM\emm_next\node_modules\jest-jasmine2\build\jasmine_async.js:108:37)
 FAIL  tests/unit/utils/commonUtility.test.ts (6.407s)jest-jasmine2\build\queue_runner.js:56:12
  util_sum

I attempted to resolve the issue by installing npm i jsdom, but unfortunately, the problem persists. I even added "testEnvironment": "jsdom" to the package.json file, but the issue remains. Is there a proper solution to fix this error?

Answer №1

I encountered a similar issue, but managed to resolve it using the following method:

When testing each component that utilizes the window.print function, I included the following snippet:

describe('Test.spec.js', () => {
    let jsdomPrint;

    beforeEach(() => {
        jsdomPrint = window.print;
        jest.spyOn(window, 'print').mockImplementation(() => {});
    });

    ...

    afterEach(() => {
        window.print = jsdomPrint;
    });
});

Answer №2

To effectively stub browser-specific side effects like window.alert and print, Jest can be used to create a spy that can be monitored and cleaned up. Below is an example of how this can be done:

jest.spyOn(window, 'alert').mockReturnValue();
jest.spyOn(window, 'print').mockReturnValue();
function printTheWebPage(){
  window.print();
}
describe("print", () => {
  it('should print', function () {
    printTheWebPage();
    expect(window.print).toHaveBeenCalled();
  });
});

For more information, please refer to the following links:

https://jestjs.io/docs/en/mock-function-api#mockfnmockreturnvaluevalue

https://jestjs.io/docs/en/manual-mocks#mocking-methods-which-are-not-implemented-in-jsdom

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

I had high hopes that TypeScript's automatic type inference for constructor parameters would do the trick, but it seems to have let

You can experiment with the given code snippet at the online playground to confirm it. Consider this code: class Alpha { private beta; constructor(b: Beta) { this.beta = b; } doSomething() { ...

Implement a jQuery feature to gradually increase opacity as the user scrolls and the page loads

On a dynamically loaded page via pjax (except in IE), there are several links at the bottom. Whenever one of these hyperlinks is clicked, the page scrolls to the top while still loading. Although I am okay with this behavior, I'm curious if it' ...

Retrieving a specific key-value pair from an object within a JavaScript array

Looking to extract a specific value from an array of objects using array.map? Check out the code snippet below: let balanceInfo = students.map((student) => { if (typeof(student) === Object){ let balance = student.balance; return balanc ...

Tips for adding a background image using React refs?

Seeking assistance with setting a background for a specific div using react ref, this is my attempted code snippet: The component class structure as follows: import React from 'react'; import PropTypes from 'prop-types'; import class ...

What is the best way to attach an onClick event to a PHP-generated link?

Currently, I'm attempting to implement an onclick event on a link within a PHP file. $body2 .= '<td class="sampling-list-td download-link">' . '<a ' . 'class="sampling-list-download" ' . 'href="#" ' . ...

Error: the search variable is not defined

function sorting(type) { $("#parentDiv").empty(); $.getJSON("example_data.json", ({ Find })); function Locate(a, b) { return (a[Find.type] < b[Find.type]) ? -1 : (a[Find.type] > b[Find.type]) ? 1 : 0; }; } The example_data.j ...

What could be causing the issue with my validation for alphabetical input?

I am currently working on a registration form that only accepts alphabetical input. However, I am facing an issue where my error message appears regardless of whether I input an alphabetical or special character. According to my understanding, the code sho ...

Challenges with Typescript arise when modifying dependencies within a Firebase function, leading to compilation

Recently, I decided to update the dependencies of my Firebase functions project in order to utilize newer versions of firebase-functions and firebase-admin. However, this led to a requirement for more recent versions of TypeScript and tslint. After making ...

How to implement the Ionic ToastController without being confined to a Vue instance

I am currently facing a challenge while trying to utilize the ToastController of Ionic outside a vue instance. I have created a separate actions file which will be loaded within the vue instance, handling a request. Within this request, certain validations ...

Animate an svg icon to follow a designated path as the user scrolls

I am currently working on a project that involves animating a bee svg icon as the user scrolls through the website. The bee starts at the top and fills in a grey color line with pink as the user moves forward, and moves backward as the user scrolls back. Y ...

Is there an equivalent of numpy.random.choice in JavaScript?

The Numpy.random.choice function is a handy tool that allows you to select a sample of integers based on a specific probability distribution: >>> np.random.choice(5, 3, p=[0.1, 0, 0.3, 0.6, 0]) array([3, 3, 0]) Is there a similar feature in Java ...

What is the correct way to remove listeners in componentWillUnmount using React, and why is binding necessary in the constructor?

I'm feeling a bit perplexed, can someone explain the distinction between these two snippets of code: constructor(props) { super(props); this.state = { openPane: false } this.togglePaneHelper = this.togglePaneHelper.bind(this); ...

Attempting to access a particular nested page poses a challenge with Relative Path in VueJS / Laravel, especially when using Router History mode

Hey there! I have a blog site at www.blog.com as my root URL and I'm wondering about how to handle image paths. When linking images for the root URL, I use: For the root URL URL: www.blog.com Resource Path : public/img/blog-logo.png <img :src ...

Issues occurring with PhoneGap preventing the execution of AngularJS code

I've recently delved into learning AngularJS with PhoneGap and I have a basic HTML code along with some AngularJS snippets. While everything runs smoothly in the browser, only the HTML portion seems to work when I attempt to run it on my Android phone ...

Problem encountered with the JavaScript for loop failing to execute consistently on each iteration

Currently, I am working on a JavaScript code that alerts the count in an array of pages. The variable urls represents an array of page names, while count contains the count value. My goal is to alert the count value for each page in the urls array. Howe ...

Display validation messages when the user either clicks out of the textbox or finishes typing

Here are some validation messages: <form name="dnaform" novalidate> <div style="padding-bottom:5px" ng-show="dnaform.uEmail.$pristine || dnaform.uEmail.$valid">Active directory account </div> <div style="padding-bottom:5px;" n ...

Troubleshooting the malfunctioning AngularJS ui-view component

My ui-view isn't functioning properly, but no errors are being displayed. Can anyone help me figure out what I'm missing to make this work? This is the main template, index.html. <!DOCTYPE html> <html> <head> <meta charset= ...

Executing operations on checkboxes on a webpage without access to model files

I am facing an issue with accessing the models file due to encryption in the software. Currently, my checkboxes are implemented using Ajax within a PHP query. Since it is Ajax-based, I am unable to manipulate actions through the URL. My goal is to extract ...

When running npx ts-lint in a Docker environment, an error occurs stating that the module 'typescript' cannot be found

In the process of setting up a dockerized development environment for a node/typescript API project, I am aiming to have everything run within Docker without the need for node, npm, or modules installed on the host system. The main objective is to isolate ...

Utilize AngularJS to bind to the input field's "enter" key and automatically submit the form if the input

I have been tasked with creating a directive that allows users to navigate to the next input or button in a modal window: .directive('autoVrm', function () { return function (scope, element, attrs) { var counter = 0; ...