角度单位测试mockbackend SPEC没有预期

时间:2017-02-09 20:10:58

标签: angularjs unit-testing angular jasmine karma-jasmine

我正在使用Jasmine& Karma用于测试角应用的单元。我已经写过像这样的单元测试

it('should match request object', inject([UserService, MockBackend], (userService: UserService, mockBackend) => {
    mockBackend.connections.subscribe((connection: MockConnection) => {
        expect(connection.request.method).toEqual(RequestMethod.Post);
        expect(connection.request.json().getUserProfileRequest).toEqual({
            userid: '1234',
        });

        connection.mockRespond(new Response(new ResponseOptions({
            body: UsersMockData.GET_USER_PROFILE,
        })));
    });

    usersService.getUserProfile(1234)
        .subscribe(data => {
            expect(data).toBe(UsersMockData.GET_USER_PROFILE);
        });
}));

当我将测试用例分成两个单独的测试用例时,一切正常并且没有问题我编写了这样的代码

it('Check userProfile request', inject([UserService, MockBackend], (userService: UserService, mockBackend) => {
    mockBackend.connections.subscribe((connection: MockConnection) => {
        expect(connection.request.method).toEqual(RequestMethod.Post);
        expect(connection.request.json()getUserProfileRequest).toEqual({
            userid: '1234',
        });
    });
}));

it('check return data from service', inject([UserService, MockBackend], (userService: UserService, mockBackend) => {

 connection.mockRespond(new Response(new ResponseOptions({
                body: UsersMockData.GET_USER_PROFILE,
            })));

  usersService.getUserProfile(1234)
    .subscribe(data => {
        expect(data).toBe(UsersMockData.GET_USER_PROFILE);
    });
}));

这两个测试用例都有期望声明,但是当我执行测试用例时,我看到两个测试用例的消息 SPEC HAS NO expECTATIONS 。我想知道为什么它显示规格没有期望。

1 个答案:

答案 0 :(得分:2)

如果您没有.subscribe方法,则永远不会生成get请求,因此永远不会调用模拟后端。如果您未提供模拟响应,则对您的方法的订阅将永远不会收到值。因此,为了达到预期,每次测试必须有一定数量的最小接线。在你的情况下:

it('Check userProfile request', inject([UserService, MockBackend], (userService: UserService, mockBackend) => {
    mockBackend.connections.subscribe((connection: MockConnection) => {
        expect(connection.request.method).toEqual(RequestMethod.Post);
        expect(connection.request.json().getUserProfileRequest).toEqual({
            userid: '1234',
        });
    });

    usersService.getUserProfile(1234).subscribe(data => {});
}));

it('check return data from service', inject([UserService, MockBackend], (userService: UserService, mockBackend) => {
    mockBackend.connections.subscribe((connection: MockConnection) => {
        connection.mockRespond(new Response(new ResponseOptions({
            body: UsersMockData.GET_USER_PROFILE,
        })));
    });

    usersService.getUserProfile(1234)
        .subscribe(data => {
            expect(data).toBe(UsersMockData.GET_USER_PROFILE);
        });
}));