如何在全球范围内为茉莉花添加自定义匹配器?

时间:2018-06-02 23:41:42

标签: javascript jasmine matcher jasmine-matchers

我需要替换版本1.3中的class A { @OneToMany(mappedBy=a) private Set<B> b; } class B { @ManyToOne private A a; } class C { @ManyToOne(optional=false) @NotNull private B b; } 函数。当前的API允许将匹配器添加到jasmine.addMatchers块,但我希望能够在任何地方使用我的匹配器,而无需一次又一次地添加它们。

是否有全局方法将自己的匹配器添加到jasmine 3.1.0?

2 个答案:

答案 0 :(得分:2)

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
    );
  }
});

答案 1 :(得分:1)

请注意,我没有在jasmine 3.1中尝试过这个,但这就是我在茉莉花2.8中做同样的事情:

将其放在测试前运行的任何代码块中:

jasmine.getEnv().beforeEach(() => {
  jasmine.addMatchers({
    toBeAwesome(util, customEqualityTesters) { ... }
  })
});