所以我正在为需要使用其他地方定义的工厂的服务中的方法编写单元测试。我如何包含模拟工厂呢?
作为替代方案,我可以包含真正的工厂,但是用httpBackend捕获所有内容,但我不愿意,因为工厂本身没有经过测试。
服务:
"use strict";
rmtg.service('meetingHelper', ['Job', function(Job) {
...
this.getStatus = function (meeting, callback) {
if (!meeting.ReferencedJobs || meeting.ReferencedJobs.length < 1){
callback('Error: No Associated Jobs');
return
} else if (meeting.ReferencedJobs.length == 1){
var job = Job.get(meeting.ReferencedJobs[0]);
console.log(job);
callback('one');
}
};
到目前为止的测试:
describe("meetingHelper service", function(){
beforeEach(module("rmtg"));
var meetingHelper;
beforeEach(inject(function(_meetingHelper_, Job){
meetingHelper = _meetingHelper_;
}));
var mockMeeting = {};
var mockUser = {};
var mockScope = {};
describe('.getStatus', function () {
beforeEach(function() {
mockScope.callback = function () {
};
spyOn(mockScope, 'callback');
});
it('should call the callback function if there are no Referrenced Jobs', function () {
meetingHelper.getStatus(mockMeeting, mockScope.callback);
expect(mockScope.callback).toHaveBeenCalledWith('Error: No Associated Jobs');
});
it('should call the callback function if there is exactly one Referrenced Jobs', function () {
mockMeeting.ReferencedJobs = ["f"];
meetingHelper.getStatus(mockMeeting, mockScope.callback);
expect(mockScope.callback).toHaveBeenCalledWith('one');
});
});
答案 0 :(得分:0)
您可以在已经注册的工厂之上注册另一家工厂:
beforeEach(function() {
var mockService = ...;
var testMod = angular.module('testMod', ['rmtg'])
.value('serviceNameToMock', mockService);
module(testMod.name);
});
如评论所示,这可能更简洁:
beforeEach(function() {
var mockService = ...;
module("rmtg", { serviceNameToMock: mockService });
});
查看angular.mock.module的文档,module
采用多个参数并不是很明显,但快速查看源代码会使其更清晰。