【问题标题】:Reset execution context of method from Jasmine从 Jasmine 重置方法的执行上下文
【发布时间】:2019-01-17 12:16:38
【问题描述】:
我有现有的服务,需要用单元测试来覆盖它。
无法应对以下情况:
const exampleVariable = 'test';
export class Class {
testMethod() {
if (!exampleVariable ) {
throw Error('There is no exampleVariable!');
}
}
}
当我们遇到错误时,如何更改“exampleVariable”的值以达到这种情况?
【问题讨论】:
标签:
javascript
angular
jasmine
【解决方案1】:
我认为这不可能进行单元测试。在这个实现中,类方法依赖于外部状态(exampleVariable 的值)来完成它的工作。相反,最好将此数据作为方法参数传递:
export class Class {
testMethod(exampleVariable) {
if (!exampleVariable) {
throw new Error('There is no exampleVariable!');
}
}
}
测试看起来像这样:
let myClass = new Class();
expect(myClass.testMethod(false)).toThrow(new Error('There is no exampleVariable!'))