AngularJS服务测试(Jasmine / Karma) - 错误:意外请求:GET

时间:2015-10-25 15:57:34

标签: angularjs unit-testing jasmine

我目前正在尝试测试我使用Karma和Jasmine编写的AngularJS服务。但是,我目前遇到了$httpBackend的问题,我无法绕过它。这是我的服务和测试:

服务:

export default angular.module("api:events", [])
.factory("Events", ($http) => {
    let api = "http://localhost:5000/api/";
    let Events = {};

    Events.query = (params) => {
        return $http.get(`${api}/events`, {params: params}).then((res) => {
            return res.data;
        });
    };

    Events.get = (params) => {
        return $http.get(`${api}/events/` + params.id).then((res) => {
            return res.data;
        });
    };

    return Events;
});

测试:

describe("api:events", () => {
    let EventsFactory, $scope, http;

    beforeEach(module("app"));

    beforeEach(inject((_Events_, $rootScope, $httpBackend) => {
        EventsFactory = _Events_;
        $scope = $rootScope.$new();
        http = $httpBackend;
    }));


    it("should return an object", () => {
        let data = {};
        let url = "http://localhost:5000/api/events/:id";
        let response = { id: "12345" };

        http.whenGET(url).respond(200, response);

        data = EventsFactory.get({ id: "1"});

        expect(data).not.toEqual("12345");

        http.flush();

        expect(data).toEqual("12345");

        http.verifyNoOutstandingExpectation();
        http.verifyNoOutstandingRequest();
    });
});

我收到的错误(由于http.flush()):

Chrome 46.0.2490 (Mac OS X 10.10.5) api:events test FAILED
    Error: Unexpected request: GET http://localhost:5000/api/events/1
    No more request expected

如果我在data = EventsFactory.get({ id: "1"});之后记录数据,我会Object{$$state: Object{status: 0}}

我也试过这样调用我的服务,结果相似:

EventsFactory.get({ id: "1"}).then((result) => {
    data = result;
});

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

这里的问题是,whenXXX()模拟的expectXXX()$http方法的网址必须是字面的。人们可以直截了当地期望带有参数的URL(例如问题代码中的:id)将起作用,但事实并非如此。所以要纠正错误,只需替换:

let url = "http://localhost:5000/api/events/:id";

使用:

let url = "http://localhost:5000/api/events/1"; // `1` is the literal id

答案 1 :(得分:1)

查看verifyNoOutstandingExpectation()verifyNoOutstandingRequest()的{​​{3}}。

它说:

  

验证通过expect api定义的所有请求都已完成。

关键词有“期待api”。您没有使用“expect”API,而是使用“when”API。在使用“when”API时,您不应该在测试结束时调用这些方法中的任何一种。

documentation描述了“期望”和“何时”API之间的差异。