In my app I use the navigator object to store a string in the clipboard:
navigator.clipboard.writeText('string')
But when I write my test in Jest and mock this object I get the error:
Cannot read property 'writeText' of undefined
This is how I mock navigator in my test file:
// 🤡 Mock clipboard object
const clipboardWriteTextSpy = jest.fn()
navigator = {
clipboard: {
writeText: clipboardWriteTextSpy
}
}
Update
I also tried using global.navigator but I still have the error:
global.navigator = {
clipboard: {
writeText: clipboardWriteTextSpy
}
}
Has someone an idea how to mock this object?
The easiest way to mock non-application logic (like browser's navigator) is to write a function as part of your application and mock it. Example:
// clipboard.js
export const setClipboard = (text) => navigator.clipboard.writeText('string');
Then mock it in your test:
// some.test.js
import { setClipboard } from './clipboard';
jest.mock('./clipboard');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With