Javascript jasmine部分字符串匹配
我喜欢jasmine.objectContaining提供的部分对象匹配:Javascript jasmine部分字符串匹配,javascript,jasmine,karma-jasmine,Javascript,Jasmine,Karma Jasmine,我喜欢jasmine.objectContaining提供的部分对象匹配: mySpy({ foo: 'bar', bar: 'baz' }); expect(mySpy).toHaveBeenCalledWith(jasmine.objectContaining({ foo: 'bar' })); 弦乐有茉莉花吗?大致如下: mySpy('fooBar', 'barBaz'); expect(mySpy).toHaveBeenCalledWith(jasmine.stringC
mySpy({
foo: 'bar',
bar: 'baz'
});
expect(mySpy).toHaveBeenCalledWith(jasmine.objectContaining({ foo: 'bar' }));
弦乐有茉莉花吗?大致如下:
mySpy('fooBar', 'barBaz');
expect(mySpy).toHaveBeenCalledWith(jasmine.stringContaining('foo'), jasmine.any(String));
我想看一个特定的参数,而不必求助于mySpy.calls的断言:
mySpy('fooBar', 'barBaz');
expect(mySpy.calls.argsFor(0)[0]).toContain('foo');
茉莉花里没有这种东西。但是您可以利用在Jasmine中创建自定义匹配器的功能来实现这一点 下面是一个小的工作示例: 你的工厂
angular.module('CustomMatchers', []).factory('AnotherService', function(){
return{ mySpy: function(a, b){ } }
});
angular.module('CustomMatchers').factory('MyService', function(AnotherService){
return{
myFunction: function(a, b){
AnotherService.mySpy(a, b);
}
}
});
使用自定义匹配器创建测试用例
describe('Service: MyService', function() {
beforeEach(module('CustomMatchers'));
describe('service: MyService', function() {
beforeEach(inject(function(_MyService_, _AnotherService_) {
MyService = _MyService_;
AnotherService = _AnotherService_;
spyOn(AnotherService, 'mySpy');
jasmine.addMatchers({
toContain: function() {
return {
compare: function(actual, expected){
var result = { pass: actual.includes(expected) };
if(result.pass) {
result.message = "Success: Expected first arguments '" + actual + "' to contain '"+ expected +"'.";
} else {
result.message = "Failour: Expected first arguments '" + actual + "' to contain '"+ expected +"'.";
}
return result;
}
}
}
});
}));
it('expect AnotherService.mySpy toHaveBeenCalled', function() {
MyService.myFunction('fooBar', 'barBaz');
//This should pass
expect(AnotherService.mySpy.calls.argsFor(0)[0]).toContain('foo');
//This should fail
expect(AnotherService.mySpy.calls.argsFor(0)[0]).toContain('helloWorld');
});
});
});
希望这有帮助 从Jasmine 2.2开始,您可以使用 例如:
mySpy('fooBar', 'barBaz');
expect(mySpy).toHaveBeenCalledWith(jasmine.stringMatching('foo'), jasmine.any(String));
请注意,参数是要匹配的正则表达式。对于简单的“contains”,直接传递字符串(使用特殊的regex字符转义),但它可以做更多的事情:
// Expect first parameter to be a string *starting* with "foo"
expect(mySpy).toHaveBeenCalledWith(jasmine.stringMatching(/^foo/), jasmine.any(String));
您可以使用toString()和match()函数执行此操作
expect(control.errors.pattern.requiredPattern).toString().match('^[+]*[(]{0,1}[0-9]{1,4}[)]{0,1}[-\S\./0-9]*$');
可能重复的