您如何在玩笑中模拟global.navigator.onLine
。
我的笑话版本是最新的24.9.0
我已经尝试过
global.navigator = {
onLine: false,
}
并使用jest.fn().mockImplementation(() => ({onLine: false}))
他们似乎仍然为navigator.onLine返回[C0
true
方法来模拟jest.spyOn()
的只读属性onLine
的值。例如:
navigator
:
index.ts
export function main() { if (navigator.onLine) { console.log('online'); } else { console.log('offline'); } }
:
index.spec.ts
单元测试结果覆盖率100%:
import { main } from './'; describe('main', () => { beforeEach(() => { jest.restoreAllMocks(); }); test('should log "online"', () => { const logSpy = jest.spyOn(console, 'log'); jest.spyOn(navigator, 'onLine', 'get').mockReturnValueOnce(true); main(); expect(logSpy).toBeCalledWith('online'); }); test('should log "offline"', () => { const logSpy = jest.spyOn(console, 'log'); jest.spyOn(navigator, 'onLine', 'get').mockReturnValueOnce(false); main(); expect(logSpy).toBeCalledWith('offline'); }); });
源代码: PASS src/stackoverflow/58603653/index.spec.ts (10.016s)
main
✓ should log "online" (14ms)
✓ should log "offline" (7ms)
console.log node_modules/jest-mock/build/index.js:860
online
console.log node_modules/jest-mock/build/index.js:860
offline
----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.ts | 100 | 100 | 100 | 100 | |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 11.259s