我编写了一个类PerlRegExp
,继承了RegExp
,并添加了一个replace
方法。运行使用jest
编写的测试时,收到意外错误TypeError: p.replace is not a function
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
可以正常运行,除了测试过程中出现此错误外,请帮帮我。
答案 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);
}
}