带有HTTP异步的Angular 5服务单元测试

时间:2018-08-24 09:29:38

标签: angular

我有以下服务

export class AuthService {
    constructor(private http: HttpClient) {}

    login(email: string, password: string) {
        return this.http.post<any>(environment.url.login, {'username': email, 'password': password}, {})
        .map(async (loginRequest) => {
            // login successful if there's a jwt token in the response
            if (loginRequest && loginRequest.token) {
                localStorage.setItem('token', loginRequest.token);
            }
            return loginRequest.token;
        })
        .pipe(retry(0));
    }
}

我想为此编写一个单元测试。我到现在为止:

describe('AuthenticationService', () => {
    let httpClientSpy;
    let authenticationService;

    beforeEach(() => {
        // Create a fake HttpClient object with a `post()` spy
        httpClientSpy = jasmine.createSpyObj('HttpClient', ['post']);

        authenticationService = new AuthenticationService(<any> httpClientSpy);

        // bypass localstorage functions to mockLockalStorage
        spyOn(localStorage, 'removeItem')
            .and.callFake(mockLocalStorage.removeItem);
        spyOn(localStorage, 'getItem')
            .and.callFake(mockLocalStorage.getItem);
    });

    it('#login should return observable of token', (done) => {
        httpClientSpy.post.and.returnValue(of({token}));

        const login = authenticationService.login('Username', '123489');
        expect(httpClientSpy).toHaveBeenCalled(); 

        // todo: check return value

        done();
    });
});

这会导致错误::可能是间谍,但得到了Object({post:HttpClient.post上的间谍})。

忽略expect(httpClientSpy).toHaveBeenCalled();

    it('#login should return observable of token', (done) => {
        httpClientSpy.post.and.returnValue(of({token}));

        const login = authenticationService.login('Username', '123489');

        login.subscribe(response => {
            expect(response).toBe(of({token}));
        });

        done();
    });
});

得出以下结果:预期[object Promise]是ScalarObservable

我已经看到在每个“ it(...)”中使用模拟和间谍以及注入服务进行不同的单元测试的可能性,我已经阅读了Angular的测试章节,但是我只是不知道这应该如何工作。请帮助我。

1 个答案:

答案 0 :(得分:-1)

由于评论还不够,让我在第二个问题的答案中进行扩展:

it('#login should return observable of token', (done) => {
    const mock = of({token});
    httpClientSpy.post.and.returnValue(mock);

    login.subscribe(response => {
        expect(response).toBe(mock);
        done();
    });

    const login = authenticationService.login('Username', '123489');
});