我经常进行单元测试,我需要比较两个矩对象。我希望我们使用 moment 的内置函数 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,
};
},
});
Run Code Online (Sandbox Code Playgroud)
但是,我无法真正让它在我的单元测试中工作......当我尝试以下测试代码时:
import moment from "moment";
import "../jest-matchers/moment";
describe("Moment matcher", …Run Code Online (Sandbox Code Playgroud)