use*_*820 11 unit-testing mocking spy angular
假设我有一个角度为6的组件,其方法test返回一些值:
import { doSomething } from './helper';
@Component({
...
})
export class AppComponent {
test() {
const data = doSomething(1);
return data.something ? 1: 2;
}
}
Run Code Online (Sandbox Code Playgroud)
doSomething 只是一个简单的辅助函数:
export function doSomething() {
return { something: 1 };
}
Run Code Online (Sandbox Code Playgroud)
是否可以在单元测试中模拟或监视此函数(因此我可以控制其returnValue)?或者我是否必须更改组件中的方法?
请注意:doSomething()可以是lodash函数,const,类等.我只是尽量保持示例尽可能简单.
我试过的事情:
SpyOn 不起作用,因为函数没有附加到任何东西
将mock函数导入给出的imports数组中TestBed.configureTestingModuleUnexpected value 'doSomething' imported by the module 'DynamicTestModule'. Please add a @NgModule annotation.
为它创建服务有效,但必须为每个导入的函数创建服务感到愚蠢
小智 12
在您的spec文件中以这种方式导入帮助程序:
import * as helper from './helper';
Run Code Online (Sandbox Code Playgroud)
在你的it()中你可以监视辅助对象并返回请求的值:
spyOn(helper, 'doSomething').and.returnValue({});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6288 次 |
| 最近记录: |