【问题标题】:testing a service call in jasmine在茉莉花中测试服务调用
【发布时间】: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() 已定义,如果我在组件本身中将其注销)

非常感谢任何帮助。

【问题讨论】:

标签: javascript angular jasmine


【解决方案1】:

作者:

我仍然不确定出了什么问题。但是我可以通过将class MockCardService extends CardService { 更改为let MockCardService 并在整个过程中使用该变量来解决此问题。祝遇到这种情况的人好运!

【讨论】:

    【解决方案2】:

    MockCardService.getCardDetails() 应该返回一个 Observable,所以你可以在组件中运行 subscribe。

    【讨论】:

    • 我尝试更改我的模拟 getCardDetails 以返回一个像这样的 observable: return getCardDetails(): any { return Observable.of([{ 0: 'card1' }, { 1: 'card2' }] ); } 。仍然给我错误 TypeError: undefined is not a constructor (evalating 'Observable_1.Observable.of([{ 0: 'card1' }, { 1: 'card2' }])') 不幸的是
    • 我用我如何尝试您的解决方案更新了问题
    • 你导入 Observable 了吗? import { Observable } from 'rxjs/Observable';你在测试中也需要它。
    • 在两个文件中从 'rxjs/Rx' 导入 { Observable }; ,是的,我在服务和测试中都导入它:(
    • 在将原始帖子设为可观察后更新了新错误
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-27
    • 2017-01-04
    相关资源
    最近更新 更多