首页 > 解决方案 > 如何在全球范围内向茉莉花添加自定义匹配器?

问题描述

我需要替换jasmine.addMatchers1.3 版中的功能。当前的 API 允许将匹配器添加到describe块中,但我希望能够在任何地方使用我的匹配器,而无需一次又一次地添加它们。

有没有一种将自己的匹配器添加到 jasmine 3.1.0的全局方法?

标签: javascriptjasminematcherjasmine-matchers

解决方案


https://github.com/JamieMason/add-matchers可用于编写适用于所有版本的 Jasmine 以及 Jest 的匹配器。

var addMatchers = require('add-matchers');

addMatchers({
  // matcher with 0 arguments
  toBeEvenNumber: function(received) {
    // received : 4
    return received % 2 === 0;
  },
  // matcher with 1 argument
  toBeOfType: function(type, received) {
    // type     : 'Object'
    // received : {}
    return Object.prototype.toString.call(received) === '[object ' + type + ']';
  },
  // matcher with many arguments
  toContainItems: function(arg1, arg2, arg3, received) {
    // arg1     : 2
    // arg2     : 15
    // arg3     : 100
    // received : [100, 14, 15, 2]
    return (
      received.indexOf(arg1) !== -1 &&
      received.indexOf(arg2) !== -1 &&
      received.indexOf(arg3) !== -1
    );
  }
});

推荐阅读