【发布时间】:2012-08-13 20:49:07
【问题描述】:
有很多文档展示了如何将匹配器添加到 Jasmine 规范(例如here)。
有没有人找到将匹配器添加到整个环境的方法?我想创建一组有用的匹配器,以供任何和所有测试调用,而无需在我的规范中使用 copypasta。
目前正在对源代码进行逆向工程,但如果有的话,更愿意尝试一种可靠的方法。
【问题讨论】:
有很多文档展示了如何将匹配器添加到 Jasmine 规范(例如here)。
有没有人找到将匹配器添加到整个环境的方法?我想创建一组有用的匹配器,以供任何和所有测试调用,而无需在我的规范中使用 copypasta。
目前正在对源代码进行逆向工程,但如果有的话,更愿意尝试一种可靠的方法。
【问题讨论】:
当然,您只需调用beforeEach(),根本没有任何规范范围,并在那里添加匹配器。
这将全局添加一个toBeOfType 匹配器。
beforeEach(function() {
var matchers = {
toBeOfType: function(typeString) {
return typeof this.actual == typeString;
}
};
this.addMatchers(matchers);
});
describe('Thing', function() {
// matchers available here.
});
我创建了一个名为 spec_helper.js 的文件,其中包含自定义匹配器之类的内容,我只需在运行规范套件的其余部分之前将其加载到页面上。
【讨论】:
javascript beforeEach(function(){ jasmine.addMatchers({ toEqualData: function() { return { compare: function(actual, expected) { return { pass: angular.equals(actual, expected) } } } } }); });
jasmine.Matchers.prototype,但实际上并没有断言语句。我的意思是:expect(false).toBeTruthyCustom() 将执行,但不会产生失败。
这是 jasmine 2.0+ 的一个:
beforeEach(function(){
jasmine.addMatchers({
toEqualData: function() {
return {
compare: function(actual, expected) {
return { pass: angular.equals(actual, expected) };
}
};
}
});
});
请注意,这使用了 Angular 的 angular.equals。
【讨论】:
编辑:我不知道这是一个可能会发生变化的内部实现。使用风险自负。
jasmine.Expectation.addCoreMatchers(matchers)
【讨论】:
根据之前的答案,我为 angular-cli 创建了以下设置。我的匹配器中还需要一个外部模块(在本例中为 moment.js)
注意在这个例子中,我添加了一个equalTester,但它应该与客户匹配器一起工作
创建一个文件src/spec_helper.ts,内容如下:
// Import module
import { Moment } from 'moment';
export function initSpecHelper() {
beforeEach(() => {
// Add your matcher
jasmine.addCustomEqualityTester((a: Moment, b: Moment) => {
if (typeof a.isSame === 'function') {
return a.isSame(b);
}
});
});
}
然后,在src/test.ts 导入initSpecHelper() 函数添加执行它。我把它放在 Angular 的 TestBed init 之前,它似乎工作得很好。
import { initSpecHelper } from './spec_helper';
//...
// Prevent Karma from running prematurely.
__karma__.loaded = function () {};
// Init our own spec helper
initSpecHelper();
// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
BrowserDynamicTestingModule,
platformBrowserDynamicTesting()
);
//...
【讨论】: