Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

reactjs - jest not implemented window.alert()

I have written a test for my API with jest. I added a function that calls my API in the test file as below:

import AuthManager from "../Client/Modules/Auth/AuthManager";

and use it as below:

test("login api resolves true", () => {
  return expect(AuthManager.login("test", "test")).resolves.toMatchObject(
    expect.objectContaining({
      accessToken: expect.any(String),
      email: expect.any(String),
      expiresIn: expect.any(Number),
      refreshToken: expect.any(String),
      userFullName: expect.any(String),
      userId: expect.any(Number)
    })
  );
});

My test passes, but I have an error as below:

Error: Not implemented: window.alert

How do I solve this problem?

question from:https://stackoverflow.com/questions/55088482/jest-not-implemented-window-alert

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The default test environment for Jest is a browser-like environment provided by jsdom.

jsdom implements most of what an actual browser would provide (including the global window object), but it doesn't implement everything.

Specifically for this case, jsdom does not implement window.alert, and instead throws an Error when it is called as can be seen in the source code here.


As long as you know why your code is launching the alert and know that your test is working properly aside from the Error then you can suppress the Error by providing an empty implementation for window.alert:

test("login api resolves true", () => {
  const jsdomAlert = window.alert;  // remember the jsdom alert
  window.alert = () => {};  // provide an empty implementation for window.alert
  return expect(AuthManager.login("test", "test")).resolves.toMatchObject(
    expect.objectContaining({
      accessToken: expect.any(String),
      email: expect.any(String),
      expiresIn: expect.any(Number),
      refreshToken: expect.any(String),
      userFullName: expect.any(String),
      userId: expect.any(Number)
    })
  );  // SUCCESS
  window.alert = jsdomAlert;  // restore the jsdom alert
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...