gpt4 book ai didi

mocking - Jest 模拟全局 navigator.onLine

转载 作者:行者123 更新时间:2023-12-04 14:34:03 25 4
gpt4 key购买 nike

你是怎么 mock 的global.navigator.onLine为 React 开 Jest 。

我的jest版本是最新的24.9.0
我试过了

global.navigator = {
onLine: false,
}

并使用 jest.fn().mockImplementation(() => ({onLine: false}))
他们似乎还是回来了 truenavigator.onLine

最佳答案

您可以使用 jest.spyOn(object, methodName, accessType?)模拟只读属性值的方法 onLinenavigator .
此外,与UI库无关reactjs .

Since Jest 22.1.0+, the jest.spyOn method takes an optional third argument of accessType that can be either 'get' or 'set', which proves to be useful when you want to spy on a getter or a setter, respectively.



例如:
index.ts :

export function main() {
if (navigator.onLine) {
console.log('online');
} else {
console.log('offline');
}
}
index.spec.ts :

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');
});
});

100% 覆盖率的单元测试结果:

 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

源代码: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58603653

关于mocking - Jest 模拟全局 navigator.onLine,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58603653/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com