Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking the navigator object

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?

like image 702
johannchopin Avatar asked Sep 02 '26 13:09

johannchopin


1 Answers

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');
like image 71
Dimitri L. Avatar answered Sep 05 '26 03:09

Dimitri L.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!