开玩笑中的自定义匹配器 [英] Custom matcher in jest

查看:18
本文介绍了开玩笑中的自定义匹配器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Jest 中创建一个类似于 stringMatching 的自定义匹配器,但它接受空值.但是,文档没有展示如何重用现有的匹配器.到目前为止,我有这样的事情:

I'm trying to create a custom matcher in Jest similar to stringMatching but that accepts null values. However, the docs don't show how to reuse an existing matcher. So far, I've got something like this:

expect.extend({
    stringMatchingOrNull(received, argument) {
        if (received === null) {
            return {
                pass: true,
                message: () => 'String expected to be null.'
            };
        }

        expect(received).stringMatching(argument);
    }
});

我不确定这是正确的方法,因为当我调用 stringMatching 匹配器时我没有返回任何内容(建议使用 此处).当我尝试使用这个匹配器时,我得到:expect.stringMatchingOrNull is not a function,即使这是在同一个测试用例中声明的:

I'm not sure this is the correct way to do it because I'm not returning anything when I call the stringMatching matcher (this was suggested here). When I try to use this matcher, I get: expect.stringMatchingOrNull is not a function, even if this is declared in the same test case:

expect(player).toMatchObject({
    playerName: expect.any(String),
    rank: expect.stringMatchingOrNull(/^[AD]$/i)
    [...]
});

请问,有人可以帮我展示正确的方法吗?

Please, can somebody help me showing the correct way to do it?

我正在使用 Jest 20.0.4 和 Node.js 7.8.0 运行测试.

I'm running the tests with Jest 20.0.4 and Node.js 7.8.0.

推荐答案

有两种不同的方法与 expect 相关.当您调用 expect(value) 时,您会得到一个带有 matchers 方法的对象,您可以将其用于各种断言(例如 toBe(value)、<代码>toMatchSnapshot()).另一种方法直接在expect上,基本上都是辅助方法(expect.extend(matchers)就是其中之一).

There are two different kinds of methods that are related to expect. When you call expect(value) you get an object with matchers methods that you can use for various assertions (e.g. toBe(value), toMatchSnapshot()). The other kind of methods are directly on expect, which are basically helper methods (expect.extend(matchers) is one of them).

使用 expect.extend(matchers) 你添加第一种方法.这意味着它不能直接在 expect 上使用,因此会出现错误.您需要按如下方式调用它:

With expect.extend(matchers) you add the first kind of method. That means it's not available directly on expect, hence the error you got. You need to call it as follows:

expect(string).stringMatchingOrNull(regexp);

但是当你调用它时,你会得到另一个错误.

But when you call this you'll get another error.

TypeError: expect(...).stringMatching is not a function

这次您尝试使用 expect.stringMatching(regexp) 作为匹配器,但它是 expect 上的辅助方法之一,它为您提供一个伪值,该值将被接受为与匹配器匹配的任何字符串值正则表达式.这允许您像这样使用它:

This time you're trying to use use expect.stringMatching(regexp) as a matcher, but it is one of the helper methods on expect, which gives you a pseudo value that will be accepted as any string value that would match the regular expression. This allows you to use it like this:

expect(received).toEqual(expect.stringMatching(argument));
//     ^^^^^^^^          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//      string                   acts as a string

这个断言只会在它失败时抛出,这意味着当它成功时函数会继续并且不会返回任何东西(undefined)并且 Jest 会抱怨你必须返回一个带有 pass 的对象 和一个可选的 message.

This assertion will only throw when it fails, that means when it's successful the function continues and nothing will be returned (undefined) and Jest will complain that you must return an object with pass and an optional 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

您需要考虑的最后一件事是使用 .not 在匹配器之前.当使用 .not 时,您还需要在您在自定义匹配器中进行的断言中使用 .not ,否则它将错误地失败,当它应该通过时.幸运的是,这非常简单,因为您可以访问 this.isNot.

One last thing you need to consider, is using .not before the matcher. When .not is used, you also need to use .not in the assertion you make inside your custom matcher, otherwise it will fail incorrectly, when it should pass. Luckily, this is very simple as you have access to 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 }
    }
});

请注意,message 仅在断言未产生正确结果时显示,因此最后一个 return 不需要消息,因为它总是会通过.错误消息只能出现在上面.您可以通过在 repl.it 上运行此示例来查看所有可能的测试用例和由此产生的错误消息.

Note that the message is only shown when the assertion did not yield the correct result, so the last return does not need a message since it will always pass. The error messages can only occur above. You can see all possible test cases and the resulting error messages by running this example on repl.it.

这篇关于开玩笑中的自定义匹配器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆