TypeError:service.getValue不是函数
public Set<Mobile> search(Set<Mobile> mobiles, OperatingSystem os,
Brand brand,Display display, Style style) {
Set<Mobile> result = new HashSet<>();
for (Set<Mobile> mobile: mobiles) {
if ((os == null || os.equals(mobile.getOs()))
&& (brand == null || brand.equals(mobile.getBrand()))
&& (display == null || display.equals(mobile.getDisplay()))
&& (style == null || style.equals(mobile.getStyle()))) {
result.add(mobile);
}
}
return result;
}
单元测试:
let data: string;
@Injectable()
export class MyService {
constructor() {
myOtherObservableReturning.subscribe((data: mydata) => {
data.items.forEach((item: Object) => {
.....
}
...
...
});
}
public getValue() { return 'HelloWorld'; }
}
我无法弄清楚为什么单元测试无法找到函数let service: MyService;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
{ provide: MyService, useValue: { data: Observable.of(dataStub) } }
]
});
service = TestBed.get(MyService);
});
it('should be created', () => {
expect(service).toBeTruthy();
console.log(JSON.stringify(service));
//LOG: '{"params":{"_isScalar":true,"scheduler":null}}'
});
it('should call getValue', () => {
//TypeError: service.getValue is not a function
expect(service.getValue()).toBe('HelloWorld');
});
,我已经在服务文件中导入并检查了它。
答案 0 :(得分:0)
确保您提供了service: MyService
的类型。如果未指定type,则Typescript仅假定变量为any
类型。
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
{ provide: MyService, useValue: { data: Observable.of(dataStub) } }
]
});
service: MyService = TestBed.get(MyService);
});
答案 1 :(得分:0)
问题已解决:我需要将data.items
初始化为空数组。这是未定义的,这就是错误Cannot read property 'forEach' of undefined
弹出的原因。