如何在Angular 5茉莉花/业力测试用例中的beforeeach中调用模拟服务

时间:2018-11-19 14:09:30

标签: unit-testing angular5 karma-jasmine

在beforeEach函数内部调用模拟服务时,我遇到了一个问题。 为了从登录名获取访问令牌,因此我需要针对spec文件中的所有功能运行该模拟服务,以便我们可以使其有序地运行。

beforeEach(inject([LoginService, MockBackend], (Service: LoginService, mockBackend: MockBackend) => {
    loginService = Service;
    backend = mockBackend;

    it('#login should call endpoint and return it\'s result', (done) => {
        backend.connections.subscribe((connection: MockConnection) => {
            const options = new ResponseOptions({
                body: JSON.stringify({ success: true })
            });
            connection.mockRespond(new Response(options));
            // Check the request headers
            expect(connection.request.headers.get('Content-Type')).toEqual('application/json');
        });

        loginService.login('new', 'secret')
        .subscribe((response) => {
            sessionStorage.setItem('token', JSON.stringify(response.token));
            done();
            fixture = TestBed.createComponent(DashboardComponent);
            router.initialNavigation();
            component = fixture.componentInstance;
            fixture.detectChanges();
        },
        (error) => {
            expect(error).toThrowError();
        });
    });
}));

0 个答案:

没有答案