如何期望httpReq.request.headers.get('authorization')。toBeTruthy()?

时间:2019-01-03 09:15:06

标签: angular unit-testing angular6 angular-services angular-http-interceptors

我在完成拦截器的单元测试时遇到问题,因为它告诉我httpReq.request.headers.get('authorization')。toBeTruthy()必须是tobefalsy()。即使我将令牌提供给它,然后将该令牌附加到授权令牌头中,如下面的代码所示,但这给了我错误。这是拦截器服务代码:

`

export class TokenInterceptorService implements HttpInterceptor {
    constructor(private auth: CoreService) {
    }
    intercept(req: HttpRequest<any>, next: HttpHandler) {
        if (this.auth.getToken()) {
            req = req.clone({
                setHeaders: {
                    authorization: `Token ${this.auth.getToken()}`
                }
            });
        }
        return next.handle(req);
    }
}

`

我尝试了不同的方法来纠正此错误,甚至我调试了此代码令牌,但当我们期望这是事实时,这告诉我令牌为空

这是规格文件的代码

`

 it('should add a Authorization token to the authorization header', () => {
        coreService.setToken('this is my dummy token');
        const token = coreService.getToken();
        const spy = coreSpy.getToken();
        const someData = { data: 'someData ' };
        http.get('localhost:3000/anonymous/user').subscribe((data) => {
            expect(data).toEqual(someData);
        });
        const httpReq = httpTestingController.expectOne('localhost:3000/anonymous/user');
        expect(httpReq.request.method).toBe('GET');
        expect(httpReq.request.headers.get('authorization')).toBeTruthy();
        expect(httpReq.request.headers.get('authorization')).toBe(`Token ${token}`);
        httpReq.flush(someData);
        httpTestingController.verify();
    });

`

预期结果是必须告诉我,我们获得授权是对的。

1 个答案:

答案 0 :(得分:-1)

我认为我们遇到了同样的问题,最后我们决定仅对请求进行单元测试并验证,使用间谍而不是测试来调用带有正确参数的req.clone,而不是测试,该克隆使用参数来更改该请求。