AngularJS Service Test (Jasmine/Karma) - Error: Unexpected request: GET

AngularJS Service Test (Jasmine/Karma) - Error: Unexpected request: GET

我目前正在尝试测试我使用 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;
});

有什么想法吗?

查看 documentation 中的 verifyNoOutstandingExpectation()verifyNoOutstandingRequest()

它说:

Verifies that all of the requests defined via the expect api were made.

关键词有"expect api"。你用的不是 "expect" API,你用的是 "when" API。使用 "when" API.

时,不应在测试结束时调用这两种方法中的任何一种

documentation描述了"expect"和"when"之间的区别API。

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

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

与:

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