Žygimantas
Žygimantas

Reputation: 331

confirm() click simulation "yes or no" in vue jest

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?

Upvotes: 1

Views: 1896

Answers (1)

Teneff
Teneff

Reputation: 32158

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

Upvotes: 4

Related Questions