angular - 在 Angular 中,我为什么要使用 jasmine.createSpyObj 而不是简单地将对象传递给提供者的 useValue?
问题描述
我刚刚开始使用 Angular 和单元测试,我想测试Component
一个依赖于ActivatedRoute
.
我Component
有一个ngOnInit
看起来像这样的方法:
async ngOnInit() {
const id = Number(this.route.snapshot.paramMap.get('id'));
//get data using the id
}
所以在我的测试beforeEach
功能中,我试图像这样设置测试平台(注意,这是在我开始测试之前):
let mockRoute;
beforeEach(async () => {
//this example didn't work, the test failed trying to reach the .get('id') call
mockRoute = jasmine.createSpyObj('mockRoute', ['snapshot.paramMap.get']);
await TestBed.configureTestingModule({
providers: [{ provide: ActivatedRoute, mockRoute }],
declarations: [ MyComponentToTest ]
})
.compileComponents();
});
我之所以使用它jasmine.createSpyObj
是因为我遵循了一个复数示例,但是在上面的示例不起作用之后,我最终在互联网上找到了这个:
beforeEach(async () => {
//this example worked
await TestBed.configureTestingModule({
providers: [
{
provide: ActivatedRoute,
useValue: {
snapshot: {
paramMap: {
get: () => 1
}
}
}
}],
declarations: [ MyComponentToTest ]
})
.compileComponents();
});
我看到了大量关于使用jasmine.createSpyObj
创建模拟的文档(和复数视频),但在我的情况下,它的效果不如useValue
,那么有人知道为什么有人会使用它jasmine.createSpyObj
吗?它是否存在用于useValue
无法使用的非常特定的用途?
解决方案
我jasmine.createSpyObj
用来模拟public
一个类的方法。public
它在模拟实例变量方面做得不好。
// the first string argument in jasmine.createSpyObj is for debugging purposes, basically it will say
// publicNameForDebugging.names was not called
// the second argument is an array of strings of public methods you would like to mock
mock = jasmine.createSpyObj('publicNameForDebugging', ['names', 'of', 'public', 'methods'])
对于您的情况,对于激活的路由,您没有要模拟的公共方法,但以下应该使用 createSpyObj 工作:
let mockRoute;
beforeEach(async () => {
//this example didn't work, the test failed trying to reach the .get('id') call
// have to put 'anything' because you might get an error if the second argument
// is an empty array
mockRoute = jasmine.createSpyObj('mockRoute', ['anything']);
// mock the instance variables and attach them to the spyObj just created
mockRoute.snapshot = {};
mockRoute.snapshot.paramMap = {};
mockRoute.snapshot.paramMap.get = () => 1;
await TestBed.configureTestingModule({
providers: [{ provide: ActivatedRoute, mockRoute }],
declarations: [ MyComponentToTest ]
})
.compileComponents();
});
推荐阅读
- amazon-web-services - 如何转换 CommaDelimitedList 参数以在 CloudFormation 中构建 ARN
- java - Libgdx 对齐不起作用
- javascript - 单击 mscrm 中的功能区按钮,在新的子案例表单中传递参数和填充字段值(选项集值)
- javascript - 无法使用 JS 单击网页元素
- build - xamarin.forms 中的项目构建错误
- hive - 如何使用 REGEXP_REPLACE 屏蔽 Hive 中的列?
- php - PHP 致命错误:未捕获错误:调用未定义函数 mysqli_result()
- python - 如何在从文件中读取()后从特定偏移量中查找(“某些文本”)
- python - Python 3 虚拟环境 - 不存在的包
- python - 在 Python 3.6 中读取 pickle 的性能比在 Python 2.7 中更差