开玩笑:模拟一个字符串属性不存在

时间:2019-12-20 18:54:51

标签: javascript typescript unit-testing jestjs

我想用Jest测试两个功能。但是,我无法将测试覆盖率提高到100%,因为我不知道如何将String.prototype.trimLeft模拟为undefined。我该怎么办?

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 }

1 个答案:

答案 0 :(得分:1)

首先,在这两种方法中,最后一条语句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