自訂相等性測試器
透過定義你自己的自訂相等性測試器,你可以自訂 Jasmine 決定兩個物件是否相等的方式。
自訂相等性測試器 是會接收兩個引數的函式。如果自訂相等性測試器知道如何比較兩個項,則應該傳回 true
或 false
。否則,應傳回 undefined
,以告知 Jasmine 的相等性測試器無法比較該兩個項。
function myCustomTester(first, second) {
if (typeof first === 'string' && typeof second === 'string') {
return first[0] === second[1];
}
}
然後,在 beforeEach
中註冊你的測試器,讓 Jasmine 得知。
beforeEach(function() {
jasmine.addCustomEqualityTester(myCustomTester);
});
現在,當你在規格中進行比較時,系統將會先檢查你的自訂相等性測試器,才會採用預設的相等性測試。請注意,如果你的自訂測試器傳回 false,將不會執行其他相等性檢查。
it('is equal using a custom tester', function () {
expect('abc').toEqual(' a ');
});
it('is not equal using a custom tester', function () {
expect('abc').not.toEqual('abc');
});
it('works even in nested equality tests', function () {
expect(['abc', '123'].toEqual([' a ', ' 1 ']);
});