首页 > 解决方案 > Confirm() 在 vue jest 中点击模拟“是或否”

问题描述

我必须使用 jest 对 vue 实例进行测试,并且测试包括一个确认弹出窗口,问题是如何模拟在弹出窗口中单击“是”。我试图使用:window.confirm = jest.fn(() => true); 并且:window.confirm = () => true; 并发明了类似的东西: wrapper.confirm = () => true; 但没有运气,也许有人有类似的问题?

标签: unit-testingvue.jsjestjs

解决方案


由于我们在 Nodejs 中运行测试,因此我们可以引用confirmasglobal.confirm和如果我们想要测试函数add,如果它在返回 true 时添加,2我们confirm可以这样做:

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);
    });
  });
});

在线工作示例


推荐阅读