gpt4 book ai didi

javascript - 开 Jest : Simulate that a string property doesn't exist

转载 作者:行者123 更新时间:2023-12-02 22:14:38 25 4
gpt4 key购买 nike

我有两个函数想用 Jest 进行测试。但是,我无法将测试覆盖率提高到 100%,因为我无法弄清楚如何模拟 String.prototype.trimLeftundefined。我能做什么?

function trimLeft (str: string): string {
if (String.prototype.trimLeft) {
return str.trimLeft()
} else {
return str.replace(/^[\s\uFEFF\xA0]+/, '')
}
return str
// else something's wrong
}

function trimRight (str: string, type: string): string {
if (String.prototype.trimRight) {
return str.trimRight()
} else {
return str.replace(/[\s\uFEFF\xA0]+$/, '')
}

return str
}

export { trimLeft, trimRight }

最佳答案

首先,最后一条语句return str在这两个方法中是无法访问的。修复它们后。这是单元测试解决方案:

index.ts:

function trimLeft(str: string): string {
if (String.prototype.trimLeft) {
return str.trimLeft();
} else {
return str.replace(/^[\s\uFEFF\xA0]+/, '');
}
}

function trimRight(str: string): string {
if (String.prototype.trimRight) {
return str.trimRight();
} else {
return str.replace(/[\s\uFEFF\xA0]+$/, '');
}
}

export { trimLeft, trimRight };

index.spec.ts:

import { trimLeft, trimRight } from './';

describe('59430114', () => {
describe('#trimLeft', () => {
it('t1', () => {
expect(trimLeft(' jestjs')).toBe('jestjs');
});
it('t2', () => {
Object.defineProperty(String.prototype, 'trimLeft', { value: undefined });
expect(trimLeft(' jestjs')).toBe('jestjs');
});
});

describe('#trimRight', () => {
it('t1', () => {
expect(trimRight('jestjs ')).toBe('jestjs');
});
it('t2', () => {
Object.defineProperty(String.prototype, 'trimRight', { value: undefined });
expect(trimRight('jestjs ')).toBe('jestjs');
});
});
});

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

 PASS  src/stackoverflow/59430114/index.spec.ts (8.386s)
59430114
#trimLeft
✓ t1 (4ms)
✓ t2 (1ms)
#trimRight
✓ t1 (1ms)
✓ t2 (1ms)

----------|----------|----------|----------|----------|-------------------|
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: 4 passed, 4 total
Snapshots: 0 total
Time: 10.085s

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

关于javascript - 开 Jest : Simulate that a string property doesn't exist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59430114/

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