Angular 4,测试服务函数调用,TypeError:xxxx不是函数

时间:2018-03-26 14:45:13

标签: angular unit-testing service

我正在尝试测试我在Angular 4中创建的服务,该服务实现如下:

import {Injectable} from '@angular/core';
import {OrderPackageResponse} from '../model/order-package-response';
import {BasketStoreHandler} from './basket-store-handler';

@Injectable()

export class OrderPackageBasketPopulator {

    private basket: BasketStoreHandler;

    constructor(private basketStoreHandler: BasketStoreHandler) {
        this.basket = basketStoreHandler;
    }

    public populateBasketWithOrderPackageResponse(
        orderPackageResponse: OrderPackageResponse
    ): void {
        // ---------------------------------
        // The function implementation
        // ---------------------------------
    }
}

测试如下:

import {OrderPackageBasketPopulator} from './order-package-basket-populator';
import {async, TestBed, inject} from '@angular/core/testing';
import {MockBasketStoreHandler} from '../test-mocks';
import {BasketStoreHandler} from './basket-store-handler';

describe('OrderPackageBasketPopulator', () => {

    let basketPopulator: OrderPackageBasketPopulator;
    let basketStoreHandler: BasketStoreHandler;

    beforeEach(() => {
        TestBed.configureTestingModule({
            providers: [
                OrderPackageBasketPopulator,
                {
                    provide: BasketStoreHandler, 
                    useClass: MockBasketStoreHandler
                }
            ]
        });
    });

    beforeEach(inject([OrderPackageBasketPopulator, BasketStoreHandler],
        (
            populator: OrderPackageBasketPopulator, 
            storeHandler: BasketStoreHandler) => {
                basketPopulator = populator;
                basketStoreHandler = storeHandler;
        }
    ));

    it('should create', async(() => {
        // ---------------------------
        // This test works
        // ---------------------------
        expect(basketPopulator).toBeTruthy();
    }));

    it('should populate basket with response', async(() => {           
        // ---------------------------
        // Assume 'response' is already initialized
        // ---------------------------
        // This call raises 'function populateBasketWithOrderPackageResponse not defined'
        // ---------------------------
        basketPopulator.populateBasketWithOrderPackageResponse(response);
    }));
});    

第二次测试引发错误:     TypeError:this.basketStoreHandler.updateBasket不是函数。

虽然第一次测试通过,看起来服务在某种程度上没有定义。我错过了一些初始化吗?

1 个答案:

答案 0 :(得分:0)

编辑:显然这是不正确的。我保持这种状态,所以有人不会发布完全相同的答案

我可能误解了这个问题。我假设BasketStoreHandler是一个可注射的元素

问题在于您注入BasketStoreHandler的方式。你会在the official angular docs中注意到,如果你在构造函数中注入一个变量

Constructor(private service: InjectableService)

您无需手动将相等性设置为内部元素。尝试删除行

private basket: BasketStoreHandler;
this.basketStoreHandler=basketStoreHandler

看看是否有所作为。

此外,这不重要,但在打字稿中public modifier is the default