ffxsam
ffxsam

Reputation: 27763

How to properly mock navigator.language in Jest?

What is the correct way to mock navigator.language in Jest, so I can test my functions that depend on the browser's locale?

I'm using this, which works, but I wonder if there's a more modern and cleaner way.

function setLanguage(language: string) {
  (window.navigator as any).__defineGetter__('language', () => language);
}

Upvotes: 1

Views: 1090

Answers (1)

Steve Beedie
Steve Beedie

Reputation: 975

With the three argument version of spyOn available in Jest 22.1.0+ you can do:

jest.spyOn(navigator, "language", "get").mockImplementation(() => "en-GB");

https://jestjs.io/docs/jest-object#jestspyonobject-methodname

Upvotes: 3

Related Questions