Last active
March 12, 2024 05:24
-
-
Save Ray-56/cfaa1ce87efe11a6f34355d49ca48742 to your computer and use it in GitHub Desktop.
Vitest 修改 window 相关属性
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { renderHook } from '@testing-library/react'; | |
import { afterEach, beforeEach, describe, expect, it, vi, expectTypeOf } from 'vitest'; | |
import { useUaParser } from '../src'; | |
describe('useUaParser', () => { | |
const userAgent = | |
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.123 Safari/537.36'; | |
beforeEach(() => { | |
const originalNavigator = { ...window.navigator }; | |
vi.spyOn(window, 'navigator', 'get').mockImplementation(() => ({ | |
...originalNavigator, | |
userAgent, | |
})); | |
}); | |
afterEach(() => { | |
vi.restoreAllMocks(); | |
}); | |
it('no params', () => { | |
const { result } = renderHook(() => useUaParser()); | |
expect(result.current[0]).toEqual({ | |
browser: { | |
name: 'Chrome', | |
major: '122', | |
version: '122.0.0.123', | |
}, | |
cpu: { | |
architecture: undefined, | |
}, | |
engine: { | |
name: 'Blink', | |
version: '122.0.0.123', | |
}, | |
os: { | |
name: 'Mac OS', | |
version: '10.15.7', | |
}, | |
device: { | |
model: 'Macintosh', | |
type: undefined, | |
vendor: 'Apple', | |
}, | |
ua: userAgent, | |
}); | |
}); | |
it('custom ua', () => { | |
const ua = 'Mozilla/5.0 (Linux; Android 11; SM-A125F) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.105 Mobile Safari/537.36'; | |
const { result } = renderHook(() => useUaParser(ua)); | |
expect(result.current[0]).toEqual({ | |
browser: { | |
name: 'Chrome', | |
major: '89', | |
version: '89.0.4389.105', | |
}, | |
cpu: { | |
architecture: undefined, | |
}, | |
engine: { | |
name: 'Blink', | |
version: '89.0.4389.105', | |
}, | |
os: { | |
name: 'Android', | |
version: '11', | |
}, | |
device: { | |
model: 'SM-A125F', | |
type: 'mobile', | |
vendor: 'Samsung', | |
}, | |
ua, | |
}); | |
}); | |
it('custom ua with other string', () => { | |
const ua = 'foo'; | |
const { result } = renderHook(() => useUaParser(ua)); | |
expect(result.current[0]).toEqual({ | |
browser: { | |
name: undefined, | |
major: undefined, | |
version: undefined, | |
}, | |
cpu: { | |
architecture: undefined, | |
}, | |
engine: { | |
name: undefined, | |
version: undefined, | |
}, | |
os: { | |
name: undefined, | |
version: undefined, | |
}, | |
device: { | |
model: undefined, | |
type: undefined, | |
vendor: undefined, | |
}, | |
ua, | |
}); | |
}); | |
}); | |
describe('useUaParser type ', () => { | |
it('useUaParser is function', () => { | |
expectTypeOf(useUaParser).toBeFunction(); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment