假设我有
spyOn($cookieStore,'get').and.returnValue('abc');
这对于我的用例来说太笼统了。任何时候我们打电话给
$cookieStore.get('someValue') --> returns 'abc'
$cookieStore.get('anotherValue') --> returns 'abc'
我想设置一个spyOn,这样我就可以根据参数得到不同的返回:
$cookieStore.get('someValue') --> returns 'someabc'
$cookieStore.get('anotherValue') --> returns 'anotherabc'
有什么建议吗?
发布于 2016-07-08 18:41:46
您可以使用callFake
spyOn($cookieStore,'get').and.callFake(function(arg) {
if (arg === 'someValue'){
return 'someabc';
} else if(arg === 'anotherValue') {
return 'anotherabc';
}
});
发布于 2020-07-17 03:29:50
对于使用版本3或更高版本的jasmine,您可以通过使用类似于sinon存根的语法来实现这一点:
spyOn(componentInstance, 'myFunction')
.withArgs(myArg1).and.returnValue(myReturnObj1)
.withArgs(myArg2).and.returnValue(myReturnObj2);
发布于 2021-12-22 18:59:38
实现相同结果的另一种方法是……(在不使用测试床的情况下编写单元测试时非常理想)在根描述块中声明spy
const storageServiceSpy = jasmine.createSpyObj('StorageService',['getItem']);
并将此spy注入到构造函数中原始服务的位置。
service = new StoragePage(storageServiceSpy)
在it()代码块中...
storageServiceSpy.getItem.withArgs('data').and.callFake(() => {})
https://stackoverflow.com/questions/37035321
复制相似问题