我目前正在尝试测试我使用 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;
});
有什么想法吗?
最佳答案
这里的问题是,提供给 $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
关于AngularJS 服务测试 (Jasmine/Karma) - 错误 : Unexpected request: GET,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33331727/