首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何存根一个jasmine模拟对象的方法?

如何存根一个jasmine模拟对象的方法?
EN

Stack Overflow用户
提问于 2012-11-30 18:01:40
回答 1查看 93.6K关注 0票数 85

根据Jasmine文档,可以像这样创建mock:

代码语言:javascript
复制
jasmine.createSpyObj(someObject, ['method1', 'method2', ... ]);

您如何存根这些方法之一?例如,如果你想测试当一个方法抛出异常时会发生什么,你会怎么做呢?

EN

回答 1

Stack Overflow用户

发布于 2018-07-13 19:32:48

基于@Eric Swanson的回答,我创建了一个更好的可读性和文档化的函数,以便在我的测试中使用。通过将参数作为函数输入,我还添加了一些类型安全性。

我建议将这段代码放在一个通用的测试类中,这样您就可以将它导入到每个需要它的测试文件中。

代码语言:javascript
复制
/**
 * 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;
}

用法如下:

代码语言:javascript
复制
import {asSpy} from "location/to/the/method";

const translator: TranslateService = jasmine.createSpyObj('TranslateService', ['getDefaultLang']);
asSpy(translator.getDefaultLang).and.returnValue(null);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13642884

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档