Mocking a Useragent in JavaScript

Mocking a useragent in javascript?

Try:

navigator.__defineGetter__('userAgent', function(){
return 'foo' // customized user agent
});

navigator.userAgent; // 'foo'

Tried it in FF2 and FF3.

How to mock window.navigator.language using jest

window.navigator and its properties are read-only, this is the reason why Object.defineProperty is needed to set window.navigator.language. It's supposed to work for changing property value multiple times.

The problem is that the component is already instantiated in beforeEach, window.navigator.language changes don't affect it.

Using Object.defineProperty for mocking properties manually will require to store original descriptor and restore it manually as well. This can be done with jest.spyOn. jest.clearAllMocks() wouldn't help for manual spies/mocks, it may be unneeded for Jest spies.

It likely should be:

let languageGetter;

beforeEach(() => {
languageGetter = jest.spyOn(window.navigator, 'language', 'get')
})

it('should do thing 1', () => {
languageGetter.mockReturnValue('de')
wrapper = shallow(<Component {...props} />)
expect(wrapper.state('currentLanguage')).toEqual('de')
})
...

How to mock window.navigator.language in jest 27

You can mock window.navigator.language using Jest as follows:

let windowSpy: jest.SpyInstance;;

beforeEach(() => {
// Spy on the read-only window function which
// returns a reference to the current window.
windowSpy = jest.spyOn(window, 'window', 'get');
});

// Clean-up the spy after every test
afterEach(() => windowSpy.mockRestore());

const setMockLanguage = (language: string) =>
// Set how you want window.navigator.language to behave
windowSpy.mockImplementation(() => ({
navigator: {
language
}
}));

test('UK date format', () => {
setMockLanguage('en-GB');

expect(window.navigator.language).toBe('en-GB');
});

test('US date format', () => {
setMockLanguage('en-US');

expect(window.navigator.language).toBe('en-US');
});

I've included some comments in the code to help.

You can see it working here.

How to mock the window navigator object while unit testing angular code

I created a method to return the navigator instead of refering it directly and then mocked the same method in the spec file.

In the component.ts file-

// method that returns navigator object
public getNavigatorReference(): any {
return navigator;
}

// method that uses the above method
private methodThatUsesNavigator(): void {
let navigatorReference = this.getNavigatorReference();
let locale = navigatorReference.language || navigatorReference.userLanguage ||
navigatorReference.browserLanguage;
...
}

In the spec file -

Object.defineProperty(navigator, 'userLanguage', {
get: function () { return 'en'; }
});


Related Topics



Leave a reply



Submit