【问题标题】:confirm() click simulation "yes or no" in vue jestConfirm() 在 vue jest 中点击模拟“是或否”
【发布时间】:2019-05-13 22:15:58
【问题描述】:

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

【问题讨论】:

  • 有趣,@dcp 刚刚向similar question 询问了alert。你们俩都采用的方法是我会采用的方法,它对我有用……我不确定为什么它对我有用,而不是对你们有用。您是否有完整的代码示例来演示该问题?
  • 我一直在玩这个问题,现在我收到一个新错误错误:未实现:window.confirm
  • Jest 默认使用jsdom 提供类似浏览器的环境,而jsdom 为许多窗口函数提供“未实现”存根,这就是错误coming from the jsdom stub

标签: unit-testing vue.js jestjs


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-05
    • 2017-09-30
    • 2021-03-20
    • 2019-11-22
    • 2021-02-14
    • 1970-01-01
    • 2020-06-08
    相关资源
    最近更新 更多