>我写了一个类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:ajanuwperl-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
可以正常运行,除了测试过程中的此错误,请帮助我,谢谢。
通过扩展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);
}
}