1

I have to make a test for a vue instance using jest and the test includes a confirm pop up, question is how to simulate click on "Yes" in the pop up. I was trying to use: window.confirm = jest.fn(() => true); and: window.confirm = () => true; and inventing something like that: wrapper.confirm = () => true; But no luck, maybe someone had similar problem?

Teneff
  • 30,564
  • 13
  • 72
  • 103
Žygimantas
  • 302
  • 2
  • 13
  • 1
    Interesting, @dcp just asked a [similar question](https://stackoverflow.com/questions/55787988) about `alert`. The approach both of you are taking is the approach I would take and it works for me...I'm not sure why it's working for me and not for you guys. Do you have a complete code sample that demonstrates the issue? – Brian Adams Apr 28 '19 at 06:28
  • I was playing around with this issue and now I'm getting a new error Error: Not implemented: window.confirm – Žygimantas Apr 30 '19 at 11:43
  • `Jest` uses `jsdom` to provide a browser-like environment by default, and `jsdom` provides "not implemented" stubs for many of the window functions, so that is the error [coming from the `jsdom` stub](https://github.com/jsdom/jsdom/blob/865ad590454dd345521722184bc298b32fa40810/lib/jsdom/browser/Window.js#L614) – Brian Adams Apr 30 '19 at 17:19

1 Answers1

4

Since we're running the tests in Nodejs we can reference confirm as global.confirm and If we want to test the function add if it adds 2 whenever confirm returns true we can do this:

const add = require('./add');

describe('add', () => {

  describe('confirm returning true', () => {
    let result;
    beforeAll(() => {
      // we define confirm to be a function that returns true
      global.confirm = jest.fn(() => true);
      result = add(1);
    });

    it('should call confirm with a string', () => {
      expect(global.confirm).toHaveBeenCalledWith(
        expect.any(String),
      );
    });


    it('should add two', () => {
      expect(result).toBe(3);
    });
  });

  describe('confirm returning false', () => {

    let result;
    beforeAll(() => {
      // we define confirm to be a function that returns false
      global.confirm = jest.fn(() => false);
      result = add(1);
    });

    it('should call confirm with a string', () => {
      expect(global.confirm).toHaveBeenCalledWith(
        expect.any(String),
      );
    });

    it('should NOT add two', () => {
      expect(result).toBe(1);
    });
  });
});

online working example

Teneff
  • 30,564
  • 13
  • 72
  • 103