在查看 Jest 问题和SO 答案后,我尝试了以下 4 个选项,但我收到 TypeScript 错误或运行时错误。我真的很想让选项 1 (spyOn) 工作。
// ------ 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;