I want to test my react project array
// this method is in the utils.ts
export const platform = (
navigator.userAgentData?.platform || navigator.platform
).toLowerCase()
export const keyboardPlayerShortcutsData = [
{
name: 'play/pause',
shortcut: platform.startsWith('mac') ? `⌘ + p` : 'Ctrl + p',
}
]
it('should generate correct keyboard player shortcuts data (mac)', () => {
// need to mock "import { platfrom } from './utils'"
expect(keyboardPlayerShortcutsData).toEqual([
{
name: 'play/pause',
shortcut: '⌘ + p',
},
])
const shortcutElement = screen.getByText('⌘ + p')
expect(shortcutElement).toBeInTheDocument()
})
it('should generate correct keyboard player shortcuts data (win)', () => {
// need to mock "import { platfrom } from './utils'"
expect(keyboardPlayerShortcutsData).toEqual([
{
name: 'play/pause',
shortcut: 'ctrl + p',
},
])
const shortcutElement = screen.getByText('ctrl + p')
expect(shortcutElement).toBeInTheDocument()
})
I use vi.mock('./utils', () => ({ platform: 'mac' })) in each test, but vi.mock will hoist to the top, so the test will fail.
I also tried, but it also not work
import { platform } from './utils'
describe('EditKeyboardShortcutSheet', () => {
vi.mock('./utils', () => ({
platform: 'MacIntel'.toLowerCase(),
}))
afterEach(() => {
vi.clearAllMocks()
})
it('should generate correct keyboard player shortcuts data (mac)', () => {
expect(keyboardPlayerShortcutsData).toEqual([
{
name: 'play/pause',
shortcut: '⌘ + p',
},
])
})
it('should generate correct keyboard player shortcuts data (win)', () => {
// ref: https://github.com/vitest-dev/vitest/discussions/4328
// got an ts error: Property 'mockReturnValue' does not exist on type 'string'.
vi.mocked(platform).mockReturnValue('Windows')
expect(keyboardPlayerShortcutsData).toEqual([
{
name: 'play/pause',
shortcut: 'ctrl + p',
},
])
})
})