javascript - 覆盖匹配器的默认 Jasmine 错误消息

标签 javascript unit-testing bdd jasmine

我想在任何匹配器失败时显示一些自定义错误消息,假设我称之为

 expect(false).toBe(true);

显然它会返回 false 并且错误信息会是

Expected false to be true 

但在这里我想显示我的自定义消息。假设我想展示

You are expecting a false but its true .

如何做到这一点。提前致谢 。

最佳答案

这不是您想要的,因为它不灵活,但它可以处理您的情况。

expect 上有一个未记录的功能 - 您可以包含自定义失败消息:

expect(false).toEqual(true, 'this is my custom error message');

在你的情况下:

expect(false).toBe(true, 'You are expecting a false but its true .');

否则,创建一个自定义匹配器(http://jasmine.github.io/2.0/custom_matcher.html):

jasmine.addMatchers({
    customToBe: function() {
        return {
            compare: function(actual, expected) {
                var result = {};
                result.pass = actual === expected;
                if (result.pass) {
                    result.message = "You are expecting a " + expected + " and its " + actual + " .";
                } else {
                    result.message = "You are expecting a " + expected + " but its " + actual + " .";
                }
            }
        };
    }
});

关于javascript - 覆盖匹配器的默认 Jasmine 错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16890184/

相关文章:

javascript - 递归地将 JSON 对象转换为 JavaScript 中的键/值数组

javascript - Node.js:Express.js 设置保持事件状态

unit-testing - react-navigation-hooks : How to test useFocusEffect

java - 通过 Hamcrest 断言集合中匹配元素的数量

testing - 通过具体类测试抽象类

cucumber - cucumber 的替代品?

javascript - 如何防止我的产品列表在父组件购物车状态更新时重新呈现?

javascript - TinyMce imagemanager 与 iframe 一起使用时不会生成图像路径

unit-testing - 如何在karma中模拟模拟服务失败?

ruby-on-rails-3 - Rails 3,RSpec 2.5 : Using should_receive or stub_chain with named scopes