根据Jasmine文档,可以像这样创建mock:
jasmine.createSpyObj(someObject, ['method1', 'method2', ... ]);
您如何存根这些方法之一?例如,如果你想测试当一个方法抛出异常时会发生什么,你会怎么做呢?
发布于 2018-07-13 19:32:48
基于@Eric Swanson的回答,我创建了一个更好的可读性和文档化的函数,以便在我的测试中使用。通过将参数作为函数输入,我还添加了一些类型安全性。
我建议将这段代码放在一个通用的测试类中,这样您就可以将它导入到每个需要它的测试文件中。
/**
* Transforms the given method into a jasmine spy so that jasmine functions
* can be called on this method without Typescript throwing an error
*
* @example
* `asSpy(translator.getDefaultLang).and.returnValue(null);`
* is equal to
* `(translator.getDefaultLang as jasmine.Spy).and.returnValue(null);`
*
* This function will be mostly used in combination with `jasmine.createSpyObj`, when you want
* to add custom behavior to a by jasmine created method
* @example
* `const translator: TranslateService = jasmine.createSpyObj('TranslateService', ['getDefaultLang'])
* asSpy(translator.getDefaultLang).and.returnValue(null);`
*
* @param {() => any} method - The method that should be types as a jasmine Spy
* @returns {jasmine.Spy} - The newly typed method
*/
export function asSpy(method: () => any): jasmine.Spy {
return method as jasmine.Spy;
}
用法如下:
import {asSpy} from "location/to/the/method";
const translator: TranslateService = jasmine.createSpyObj('TranslateService', ['getDefaultLang']);
asSpy(translator.getDefaultLang).and.returnValue(null);
https://stackoverflow.com/questions/13642884
复制相似问题