【发布时间】:2018-04-14 11:11:39
【问题描述】:
我正在尝试为调用服务的函数编写单元测试。但是我遇到了错误:TypeError: undefined is not a constructor
我要测试的是一个服务调用,成功后会设置变量“cards”的值。
我已经为服务 (CardService) 创建了适当的模拟,您可以在下面的规范文件中看到它
test.component.spec.ts
class MockCardService extends CardService {
constructor() {
super(null); // null is the http in service's constructor
}
getCardDetails(): any {
return Observable.of([{ 0: 'card1' }, { 1: 'card2' }]);
}
}
describe('MyComponent', () => {
let component: MyComponent;
let mockCardService: MockCardService;
beforeEach(() => {
mockCardService = new MockCardService();
component = new MyComponent(
mockCardService // add the mock service that runs before each test
);
});
// The failing test :(
it('should set the card variable to the value returned by the service', () => {
spyOn(mockCardService, 'getCardDetails').and.callThrough();
// Act
component.ngOnInit();
component.updateCards(); // call the function I am testing
// Assert
expect(component.cards).toConTainText('Card1');
});
还有我正在测试的函数的 component 文件:
export class MyComponent implements OnInit {
public cards: CardModel[] = [];
constructor(
private cardService: CardService,
) {
}
ngOnInit() {
this.updateCards(); // call the update card service
}
updateCards(): void {
this.cardService.getCardDetails().subscribe(
(cardsDetails) => {
this.cards = cardsDetails;
},
(err) => {
// todo: error handling
console.log(err);
}
);
}
}
每当此测试运行时,我都会收到错误消息:
TypeError: undefined is not a constructor(评估 'Observable_1.Observable.of([{ 0: 'card1' }, { 1: 'card2' }])')(第 22 行) 获取卡片详细信息 更新卡 ngOnInit
而且我不知道我做错了什么,为什么“getCardDetals.subscribe”是未定义的。由于某种原因,我提供的 MockCardService 类似乎无法正常工作。
(请注意 this.cardService.getCardDetails() 已定义,如果我在组件本身中将其注销)
非常感谢任何帮助。
【问题讨论】:
-
猜测,
this.cardService.getCardDetails()从您的模拟中返回字符串,并且该字符串没有subscribe方法。 angular2 testing using jasmine for subscribe method 的答案可能会有所帮助。
标签: javascript angular jasmine