Purpose:
- Need to iterate through different combinations of the userAgent
- Simulate navigator behavior
- Execute the test
Observation:
- I simulated the navigator.userAgent, simulation works as planned, first test executes as expected
- Second simulation is performed, but the test detects the userAgent value from the initial simulation
Function to be tested:
export const isBrowseriOS = () => {
console.log(navigator.userAgent, ' & ', navigator.vendor);
return (
navigator.vendor === 'Apple Computer, Inc.' ||
(/iPad|iPhone|iPod/.test(navigator.userAgent) &&
!window.MSStream &&
'ontouchend' in document)
);
};
Test file:
import { isBrowseriOS } from './isIOS';
const browserDevices = [
{
name: 'iPhone 12 Pro',
userAgent:
'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1',
vendor: 'Apple Computer, Inc.',
iOSDevice: true,
},
{
name: 'Samsung SM-G955U',
userAgent:
'Mozilla/5.0 (Linux; Android 8.0.0; SM-G955U Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Mobile Safari/537.36',
vendor: 'Google Inc.',
iOSDevice: false,
},
];
describe.each(browserDevices)('iOS test for $name', (device) => {
beforeEach(() => {
Object.defineProperty(window, 'navigator', {
value: {
userAgent: device.userAgent,
vendor: device.vendor,
},
});
});
afterEach(() => jest.resetAllMocks());
it(`returns ${device.iOSDevice}`, () => {
expect(isBrowseriOS()).toBe(device.iOSDevice);
});
});
Outcome: https://i.sstatic.net/OiySk.png