我经常进行单元测试,需要比较两个矩对象。我会给我们一下矩的内置函数moment.isSame(moment)进行比较。但是,这意味着我的断言将如下所示:
expect(moment1.isSame(moment2)).toBeTrue();
我不太喜欢这样,特别是因为失败消息的信息量较少。因此,我想编写一个自定义的笑话匹配器“ toBeSameMoment”。以下代码似乎至少可以编译:
import moment from "moment";
declare global {
namespace jest {
interface MomentMatchers extends Matchers<moment.Moment> {
toBeSameMoment: (expected: moment.Moment) => CustomMatcherResult;
}
}
}
expect.extend({
toBeSameMoment(received: moment.Moment, expected: moment.Moment): jest.CustomMatcherResult {
const pass: boolean = received.isSame(expected);
const message: () => string = () => pass ? "" : `Received moment (${received.toISOString()}) is not the same as expected (${expected.toISOString()})`;
return {
message,
pass,
};
},
});
但是,我无法在单元测试中真正使用它...当我尝试以下测试代码时:
import moment from "moment";
import "../jest-matchers/moment";
describe("Moment matcher", () => {
test("should fail", () => {
const moment1 = moment.utc();
const moment2 = moment();
expect(moment1).toBeSameMoment(moment2);
});
});
...然后出现以下错误:
error TS2339: Property 'toBeSameMoment' does not exist on type 'JestMatchersShape<Matchers<void, Moment>, Matchers<Promise<void>, Moment>>'.
不过,我不太明白这个错误。例如,这指的是什么类型的void?我曾尝试使用Google搜索,但实际上并没有找到一个好的指南。我确实注意到了这个问题:How to let know typescript compiler about jest custom matchers?,它似乎基本上是重复的,但显然还不够清楚。
我的tsconfig中包含笑话类型
与您链接的另一个问题和答案是正确的,您还可以在react-testing-library的this github comment中找到一个非常简洁的示例来说明如何扩展玩笑。
要为您的代码实现其解决方案,只需更改:
declare global {
namespace jest {
interface MomentMatchers extends Matchers<moment.Moment> {
toBeSameMoment: (expected: moment.Moment) => CustomMatcherResult;
}
}
}
收件人:
declare global {
namespace jest {
interface Matchers<R> {
toBeSameMoment(expected: moment.Moment): CustomMatcherResult
}
}
}