在我的测试中模拟/监视API调用时,我在运行Jasmine测试时遇到上述错误。以下是调用API的代码:
UploadedReleasesController.$inject = ['$log', '$scope', '$filter', '$modal', 'ReleaseService', 'TrackService', 'APP_CONFIG', 'DeliveriesService'];
function UploadedReleasesController ($log, $scope, $filter, $modal, releaseService, trackService, APP_CONFIG, deliveriesService){
.
.
.
releaseService.releases(vm.currentWorkspace).then(function (responseValues) {
vm.albums = responseValues;
if(vm.albums.length !== 0){
vm.selected.album = vm.albums[0];
其中releaseService
是我定义的服务,而releases
是我想要监视的方法之一。它需要一个字符串参数,比如说'HIGH'
。这是我的测试文件,我想模拟该调用:
describe('app module', function() {
var vm, scope, modalInstance, releaseService, trackService, deliveriesService;
beforeEach(module('app.uploadedReleases')); // Main module name
beforeEach(module('app.config'));
beforeEach(module('auth'));
beforeEach(function() {
var mockReleasesData = {
"test" : 100
}
};
releaseService = jasmine.createSpyObj("releaseService", ["releases"]);
releaseService.releases('HIGH').and.returnValue(mockReleasesData);
});
beforeEach(inject(function($controller, $log, $rootScope, $filter, APP_CONFIG) {
scope = $rootScope.$new();
modalInstance = {
close: jasmine.createSpy('modalInstance.close'),
open: jasmine.createSpy('modalInstance.open'),
dismiss: jasmine.createSpy('modalInstance.dismiss'),
result: {
then: jasmine.createSpy('modalInstance.result.then')
}
};
vm = $controller('UploadedReleasesController', {'APP_CONFIG':APP_CONFIG, '$log':$log, '$scope':scope, '$filter':$filter, '$modal':modalInstance,
'ReleaseService':releaseService, 'TrackService':trackService, 'DeliveriesService':deliveriesService});
}));
运行测试后,我收到错误:
TypeError:'undefined'不是对象(评估'releaseService.releases('HIGH')。和') 在test-release.controller.spec.js:93 TypeError:'undefined'不是对象(评估'releaseService.releases(vm.currentWorkspace).then') 未定义
以下是来自release.service.js
releaseService.releases = getReleases;
.
.
.
function getReleases(workspace){
var releases = [];
headers.Workspace = workspace; // set the workspace
var deferred = $q.defer();
// Then make $http calls and return a promise
.
.
答案 0 :(得分:2)
我看到一些可能存在问题的事情:
release
方法: releaseService.releases('HIGH').and.returnValue(mockReleasesData);
releases
方法,如果应该在这里设置返回值,那么我认为语法可能是:
releaseService.releases.and.returnValue(mockReleasesData);
然后你可以使用正确的数据在releases
上断言。
mockReleaseData
没有then
方法。由于它将从releases
退回,因此将调用then
方法: releaseService.releases(vm.currentWorkspace).then(function (responseValues)
var mockReleasesData = {
"test" : 100
},
then: function(callbackFn) {
// could call callbackFn with fake responseValues
}
};
测试的目的是什么?是运用then
匿名函数吗?通过少量重组来暴露您的逻辑,测试可能是微不足道的。
function handleResponseValues(vm, responseValues) {
vm.albums = responseValues;
if(vm.albums.length !== 0){
vm.selected.album = vm.albums[0];
}
这仍然需要then
回调调用handleResponseValues
并引用vm
和responseValues
,但会公开所有与承诺链无关的逻辑。< / p>