angular - 无法读取未定义的属性“returnValue”
问题描述
我正在根据官方 Angular文档编写我的第一个单元测试
但是,当我尝试使用他们的示例时,我在尝试测试时遇到了上述错误。我环顾四周,但找不到有关此特定错误的任何信息。
我的尝试:
import { TestBed } from '@angular/core/testing';
import { HttpClient } from '@angular/common/http';
import { VService } from './vservice';
fdescribe('VService', () => {
let VServiceSpy: jasmine.SpyObj<VService>;
beforeEach(() => {
const spy = jasmine.createSpyObj('VService', ['getAll']);
TestBed.configureTestingModule({
// this fixed an issue which is why i added it
providers: [{ provide: HttpClient, useValue: spy }]
});
VServiceSpy = TestBed.get(VService);
});
it('should be created', () => {
expect(VServiceSpy).toBeTruthy();
});
it('#getAll should return stubbed value from a spy', () => {
const stubValue = [
{
id: '1',
name: 'Repairs',
number: '000000001',
address: '1 Test Rd. Tampa, OH 44442',
phoneNumber: '111-111-1111',
emailAddress: 'test@email.com'
}
];
// here is the issue
VServiceSpy.getAll.and.returnValue(stubValue);
expect(VServiceSpy.getAll()).toBe(stubValue, 'service returned stub value');
expect(VServiceSpy.getAll.calls.count())
.toBe(1, 'spy method was called once');
expect(VServiceSpy.getAll.calls.mostRecent().returnValue)
.toBe(stubValue);
});
});
我认为这是我的服务返回可观察的问题吗?不过,我认为这很标准。我的服务没有什么特别之处。
解决方案
你很亲密。要测试服务,您需要将该服务添加到 providers 数组。所以改变这个:
TestBed.configureTestingModule({
// this fixed an issue which is why i added it
providers: [{ provide: HttpClient, useValue: spy }]
});
像这样:
TestBed.configureTestingModule({
providers: [
VService,
{ provide: HttpClient, useValue: spy }
]
});
注意:您可以在设置 HttpClient 时对其进行间谍活动,但也可以查看此处HttpClientTestingModule
详细记录的内容。
推荐阅读
- arrays - 在当前范围内没有为 struct `schema::users::columns::roles` 找到名为 `contains` 的方法
- regex - 正则表达式异常
- wpf - 如何始终通过 DataTemplate 加载相同的 UserControl 实例?
- php - PHP & Regex - 在标题(字符串)中查找特定字符串
- python - 根据列值创建列表并使用该列表从 df 中的字符串列中提取单词,而不用 for 循环覆盖行值
- ethereum - 如何返回循环和数组元素 | 函数中返回参数的数据位置必须是“内存” | 动态数组
- python - 在python中的列表框之间移动项目
- java - 适用于 Java 项目的 Azure DevOps Pipeline 与自托管代理
- go - 如何将 int 切片转换为字符串切片
- linq - 在 LINQ 中将时间跨度转换为字符串