我正在尝试在Jest中创建一个类似于stringMatching的自定义匹配器,但它接受空值.但是,文档未显示如何重用现有匹配器.到目前为止,我有这样的事情:
expect.extend({
stringMatchingOrNull(received, argument) {
if (received === null) {
return {
pass: true,
message: () => 'String expected to be null.'
};
}
expect(received).stringMatching(argument);
}
});
Run Code Online (Sandbox Code Playgroud)
我不确定这是否是正确的方法,因为我在调用stringMatching匹配器时没有返回任何内容(这是在这里建议的).当我尝试使用这个匹配器时,我得到:expect.stringMatchingOrNull is not a function,即使在相同的测试用例中声明:
expect(player).toMatchObject({
playerName: expect.any(String),
rank: expect.stringMatchingOrNull(/^[AD]$/i)
[...]
});
Run Code Online (Sandbox Code Playgroud)
拜托,有人可以帮我展示正确的方法吗?
我正在使用Jest 20.0.4和Node.js 7.8.0运行测试.
Mic*_*ngo 15
有两种不同的方法expect.当您调用时,expect(value)您将获得一个具有匹配器方法的对象,您可以将其用于各种断言(例如toBe(value),toMatchSnapshot()).另一种方法是直接开启的expect,它们基本上是辅助方法(expect.extend(matchers)就是其中之一).
随expect.extend(matchers)你添加第一种方法.这意味着它不能直接使用expect,因此你得到的错误.您需要按如下方式调用它:
expect(string).stringMatchingOrNull(regexp);
Run Code Online (Sandbox Code Playgroud)
但是当你打电话给你时,你会得到另一个错误.
TypeError: expect(...).stringMatching is not a function
Run Code Online (Sandbox Code Playgroud)
这次你试图使用use expect.stringMatching(regexp)作为匹配器,但它是一个辅助方法expect,它为你提供了一个伪值,可以接受任何与正则表达式匹配的字符串值.这允许你像这样使用它:
expect(received).toEqual(expect.stringMatching(argument));
// ^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// string acts as a string
Run Code Online (Sandbox Code Playgroud)
这个断言只会在失败时抛出,这意味着当它成功时函数继续并且不会返回任何内容(undefined)并且Jest会抱怨你必须返回一个带有pass和可选的对象message.
Unexpected return from a matcher function.
Matcher functions should return an object in the following format:
{message?: string | function, pass: boolean}
'undefined' was returned
Run Code Online (Sandbox Code Playgroud)
您需要考虑的最后一件事是.not在匹配器之前使用.在.not使用时,您还需要.not在自定义匹配器中使用的断言中使用,否则在它应该通过时它将无法正确地失败.幸运的是,这很简单,因为您可以访问this.isNot.
expect.extend({
stringMatchingOrNull(received, regexp) {
if (received === null) {
return {
pass: true,
message: () => 'String expected to be not null.'
};
}
// `this.isNot` indicates whether the assertion was inverted with `.not`
// which needs to be respected, otherwise it fails incorrectly.
if (this.isNot) {
expect(received).not.toEqual(expect.stringMatching(regexp));
} else {
expect(received).toEqual(expect.stringMatching(regexp));
}
// This point is reached when the above assertion was successful.
// The test should therefore always pass, that means it needs to be
// `true` when used normally, and `false` when `.not` was used.
return { pass: !this.isNot }
}
});
Run Code Online (Sandbox Code Playgroud)
请注意,message仅在断言未产生正确结果时才显示,因此最后一个return不需要消息,因为它将始终通过.错误消息只能在上面发生.您可以通过在repl.it上运行此示例来查看所有可能的测试用例和生成的错误消息.