我运行了用jest编写的测试,但收到了意外错误TypeError:p.replace不是一个函数。

时间:2020-02-02 08:50:54

标签: typescript jestjs

我编写了一个类PerlRegExp,继承了RegExp,并添加了一个replace方法。运行使用jest编写的测试时,收到意外错误TypeError: p.replace is not a function

PerlRegExp

export class PerlRegExp extends RegExp {
  constructor(pattern: string, flags: string) {
    super(handlePattern(pattern, flags), handleFlags(flags));
  }

  replace(string: string, replaceValue: string) {
    // ...
  }
}

测试代码

import { PerlRegExp } from "../src";

describe("PerlRegExp", () => {
  it("replace test \\u", () => {
    const p = new PerlRegExp(" (?:- (\\w) ) ", "xig");
    const r = p.replace("color-red", "\\u$1");
    expect(r).toBe("colorRed");
  });
});

测试期间出乎意料的结果

λ npm t

> perl-regexp@0.1.0 test D:\ajanuw\perl-regexp
> jest

 FAIL  test/perl-regexp.test.ts
  PerlRegExp
    × replace test \u (3ms)

  ● PerlRegExp › replace test \u

    TypeError: p.replace is not a function

      3 |   it("replace test \\u", () => {
      4 |     const p = new PerlRegExp(" (?:- (\\w) ) ", "xig");
    > 5 |     const r = p.replace("color-red", "\\u$1");
        |                 ^
      6 |     expect(r).toBe("colorRed");
      7 |   });
      8 |

      at Object.<anonymous> (test/perl-regexp.test.ts:5:17)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        4.893s, estimated 5s
Ran all test suites.
npm ERR! Test failed.  See above for more details.

我不知道问题出在哪里,因为PerlRegExp可以正常运行,除了测试过程中出现此错误外,请帮帮我。

1 个答案:

答案 0 :(得分:0)

通过扩展RegExp.prototype来解决:)

declare global {
  interface RegExp {
    replace(str: string, replaceValue: string): string;
  }
}

RegExp.prototype.replace = function(str: string, replaceValue: string) {
  // ...
};

export class PerlRegExp extends RegExp {
  constructor(pattern: string, flags: string) {
    super(handlePattern(pattern, flags), handleFlags(flags));
  }

  replace(str: string, replaceValue: string) {
    return super.replace(str, replaceValue);
  }
}