如何在 Jest 中模拟 navigator.clipboard.writeText()? [英] How to mock navigator.clipboard.writeText() in Jest?

查看:122
本文介绍了如何在 Jest 中模拟 navigator.clipboard.writeText()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在查看 Jest 问题和 SO 答案,但我遇到了 TypeScript 错误或运行时错误.我真的很想让选项 1 (spyOn) 工作.

I have tried the following 4 options after looking at Jest issues and SO answers, but I am either getting TypeScript errors or runtime errors. I would really like to get option 1 (spyOn) working.

// ------ option 1 -----
// Gives this runtime error: "Cannot spyOn on a primitive value; undefined given"
const writeText = jest.spyOn(navigator.clipboard, 'writeText');

// ------ option 2 -----
Object.defineProperty(navigator, 'clipboard', {
    writeText: jest.fn(),
});

// ------ option 3 -----
// This is from SO answer but gives a TypeScript error
window.__defineGetter__('navigator', function() {
    return {
        clipboard: {
            writeText: jest.fn(x => x)
        }
    }
})

// ------ option 4 -----
const mockClipboard = {
    writeText: jest.fn()
};
global.navigator.clipboard = mockClipboard;

推荐答案

Jest 测试是在 JSdom 环境中运行的,并没有定义所有的属性,所以你应该在监视它之前定义函数.

Jest tests are running in JSdom environment and not all of the properties are defined, but so you should define the function before spying on it.

这是一个例子:

Object.assign(navigator, {
  clipboard: {
    writeText: () => {},
  },
});

describe("Clipboard", () => {
  describe("writeText", () => {
    jest.spyOn(navigator.clipboard, "writeText");
    beforeAll(() => {
      yourImplementationThatWouldInvokeClipboardWriteText();
    });
    it("should call clipboard.writeText", () => {
      expect(navigator.clipboard.writeText).toHaveBeenCalledWith("zxc");
    });
  });
});

你也可以使用Object.defineProperty,但它接受描述符对象作为第三个参数

you can also use Object.defineProperty, but it accepts descriptors object as third parameter

Object.defineProperty(navigator, "clipboard", {
  value: {
    writeText: () => {},
  },
});

这篇关于如何在 Jest 中模拟 navigator.clipboard.writeText()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆