I love the partial object matching that jasmine.objectContaining provides:
JavaScript
x
6
1
mySpy({
2
foo: 'bar',
3
bar: 'baz'
4
});
5
expect(mySpy).toHaveBeenCalledWith(jasmine.objectContaining({ foo: 'bar' }));
6
Is there a jasmine equivalent for strings? something along the lines of:
JavaScript
1
3
1
mySpy('fooBar', 'barBaz');
2
expect(mySpy).toHaveBeenCalledWith(jasmine.stringContaining('foo'), jasmine.any(String));
3
I’d like to look at a specific argument without resorting to assertions off mySpy.calls:
JavaScript
1
3
1
mySpy('fooBar', 'barBaz');
2
expect(mySpy.calls.argsFor(0)[0]).toContain('foo');
3
Advertisement
Answer
There isn’t anything of this sort in Jasmine. But you can leverage the ability of creating a custom matcher in Jasmine for this.
Here’s a small working example:
Your Factories
JavaScript
1
12
12
1
angular.module('CustomMatchers', []).factory('AnotherService', function(){
2
return{ mySpy: function(a, b){ } }
3
});
4
5
angular.module('CustomMatchers').factory('MyService', function(AnotherService){
6
return{
7
myFunction: function(a, b){
8
AnotherService.mySpy(a, b);
9
}
10
}
11
});
12
Your test case with a custom matcher
JavaScript
1
39
39
1
describe('Service: MyService', function() {
2
beforeEach(module('CustomMatchers'));
3
describe('service: MyService', function() {
4
5
beforeEach(inject(function(_MyService_, _AnotherService_) {
6
MyService = _MyService_;
7
AnotherService = _AnotherService_;
8
9
spyOn(AnotherService, 'mySpy');
10
11
jasmine.addMatchers({
12
toContain: function() {
13
return {
14
compare: function(actual, expected){
15
var result = { pass: actual.includes(expected) };
16
if(result.pass) {
17
result.message = "Success: Expected first arguments '" + actual + "' to contain '"+ expected +"'.";
18
} else {
19
result.message = "Failour: Expected first arguments '" + actual + "' to contain '"+ expected +"'.";
20
}
21
return result;
22
}
23
}
24
}
25
});
26
27
}));
28
29
it('expect AnotherService.mySpy toHaveBeenCalled', function() {
30
MyService.myFunction('fooBar', 'barBaz');
31
//This should pass
32
expect(AnotherService.mySpy.calls.argsFor(0)[0]).toContain('foo');
33
34
//This should fail
35
expect(AnotherService.mySpy.calls.argsFor(0)[0]).toContain('helloWorld');
36
});
37
});
38
});
39
Hope this helps!