jest not implemented window.alert()

前端 未结 3 438
春和景丽
春和景丽 2021-01-03 18:50

i have written test for my api with jest . i added function that calls my api in test file as below:

import AuthManager from \"../Client/Modules/Auth/AuthMan         


        
相关标签:
3条回答
  • 2021-01-03 18:58

    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
    });
    
    0 讨论(0)
  • 2021-01-03 19:02

    I faced with window.confirm This is my solution for angular fw.

    let spyOnWindow: jasmine.Spy;
    
    beforeEach((() => {
        TestBed.configureTestingModule({
          declarations: [...],
          imports: [...],
          providers: [...]
        }).compileComponents().then(() => {
          ...
          spyOnWindow = spyOn(window,'confirm');
          ...
        });
    

    Some test case

    it('showModal testing function with delete an event', () => {
    spyOnWindow.and.returnValue(true);
    ...
    }
    
    it('showModal testing function with delete an event', () => {
    spyOnWindow.and.returnValue(false);
    ...
    }
    
    0 讨论(0)
  • 2021-01-03 19:14

    How I solved this problem is actually define the window.alert method at the top of the test file as a jest spy. This should work for any window method (in my case I was actually testing window.open).

    Be sure to call mockClear() in your test, since this is a global object and it's calls will persist across tests.

    window.alert = jest.fn();
    
    test("login api resolves true", () => {
      window.alert.mockClear();
      /* ... */
    })
    
    0 讨论(0)
提交回复
热议问题