我如何测试订阅服务的组件?

问题描述 投票:0回答:1

我对Angular中的单元测试还比较陌生。我正在使用Jasmine,但我发现API含糊不清。我正在尝试为我的组件编写好的测试,但是我陷入了如何测试订阅服务中数据的组件的困局。

//组件

ngOnInit() {
    this.store.dispatch(this.loadDatagridDataAction({data: this.authorizations}));

    this.authorizationService.initAuthorizations();
    this.authorizationService.authorizations.subscribe(authorizations => {
        this.realAuthorizations = authorizations;
        this.realAuthorizations.results.forEach(authorization => {

            const formatAuthorization = {};

            if (authorization.number) {
                formatAuthorization['number'] = authorization.number;
            }

            if (authorization.status) {
                formatAuthorization['status'] = authorization.status;

            }

            if (authorization.requesting_provider) {
                const requestingProvider = flattenObject(authorization.requesting_provider);
                formatAuthorization['requesting_provider'] = requestingProvider['name'];

            }

            if (authorization.servicing_provider) {
                const servicingProvider = flattenObject(authorization.servicing_provider);
                formatAuthorization['servicing_provider'] = servicingProvider['name'];

            }

            if (authorization.termination_date) {
                formatAuthorization['termination_date'] = authorization.termination_date;
            }

            this.formattedAuthorizations.push(formatAuthorization);
        });

    });

}

setActiveTab(tab) {
    this.store.dispatch(this.setActiveTabAction({tab}));
}

setActiveRow(row) {
    console.log(row);
}

setCurrentPage(page) {
    this.store.dispatch(this.setPaginatorCurrentPageAction({page}));
}

goBack(route) {
    console.log(route);
}

}

//服务

export class AuthorizationService {

private _authorizations = new Subject<any>();

constructor(
    private http: HttpClient,
) { }

public get authorizations() {
    return this._authorizations.asObservable();
}

public getAuthorizations() {
    const auth = '/api/enrollment/tocs/';
    return this.http.get(auth);
}

public initAuthorizations() {
    this.getAuthorizations().subscribe(data => {
        this._authorizations.next(data);
    }, error => {
        console.log('Failed to get data', error);
    });
}

}

//单元测试

describe('AuthorizationsReferralsComponent', () => {
let component: AuthorizationsReferralsComponent;
let fixture: ComponentFixture<AuthorizationsReferralsComponent>;
let storeMock;
let configurationServiceMock;
let authorizationMockService;

beforeEach(async(() => {
    storeMock = {
        select: jasmine.createSpy('select'),
        dispatch: jasmine.createSpy('dispatch'),
    };

    authorizationMockService = jasmine.createSpyObj(['getAuthorizations', 'initAuthorizations', 'authorizations']);

    configurationServiceMock = {
        getTemplateConfiguration: () => {}
    };

    TestBed.configureTestingModule({
        declarations: [ AuthorizationsReferralsComponent ],
        imports: [SidebarTableViewModule,  HttpClientTestingModule],
        providers: [
            {
                provide: Store,
                useValue: storeMock
            },
            {
                provide: ConfigurationService,
                useValue: configurationServiceMock,
            },
            {
                provide: AuthorizationService,
                useValue: authorizationMockService
            },

        ]
    })
    .compileComponents();
}));

beforeEach(() => {
    HEROES = [
      {id: 1, name: 'SpiderDude', strength: 8},
      {id: 2, name: 'Wonderful Woman', strength: 24},
      {id: 3, name: 'SuperDude', strength: 55}
    ];

    fixture = TestBed.createComponent(AuthorizationsReferralsComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
});

it('should create', () => {
    authorizationMockService.initAuthorizations.and.returnValue(of(HEROES));
    fixture.detectChanges();

    expect(fixture.componentInstance.realAuthorizations.length).toBe(3);
});

});

我收到以下错误TypeError: this.authorizationService.authorizations.subscribe is not a function

似乎认为我的get authorizations()函数不是函数。如何适当模拟服务,以便测试订阅中的语句?

 this.authorizationService.authorizations.subscribe(
angular unit-testing jasmine observable
1个回答
1
投票

现在,您的模拟服务不返回任何东西,并且您的组件期望它返回一个Observable。

在测试中,您需要以下行:

authorizationMockService.authorizations.and.returnValue(of([])

注意,上面的代码使它返回一个带空数组的Observable。如果要返回实际数据,则需要进行设置。

© www.soinside.com 2019 - 2024. All rights reserved.