gpt4 book ai didi

javascript - AngularJS 单元测试 - 未定义不是函数

转载 作者:行者123 更新时间:2023-11-28 19:21:42 24 4
gpt4 key购买 nike

我正在尝试学习如何在 Angular 内进行单元测试。对我的 Controller 进行单元测试,然后从我的服务开始。

我已经开始进行基本测试。

Controller 代码:

angular.module('app')
.controller('TestCtrl', function ($rootScope,$scope,fileLoader,ngProgress) {
$scope.test= [];
$scope.init = function(){
fileLoader.getFile("test")
.then(function(res){
//Success
console.log(res);
$scope.test= res;
}, function(err){
//Error
});

ngProgress.complete();
}

$scope.init();
$scope.title = "Test";
});

测试代码:

describe('Controller: TestCtrl', function () {

// load the controller's module
beforeEach(module('app'));

var TestCtrl,
scope,test;
test = {};
test.getFile = function(name) {
return [
{
"id": 0,
"name": "Test",
"imgName": "Test.png"
},
{
"id": 1,
"name": "Test1",
"imgName": "Test1.png"
}];
};


// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
TestCtrl= $controller('TestCtrl', {
$scope: scope,
fileLoader : test
});
}));

it('should have the correct title', function () {
expect(scope.title).toBe("Test");
});
});

我不明白为什么会出现以下错误:

TypeError: 'undefined' is not a function (evaluating 'fileLoader.getFile("test") .then') undefined

一旦解决了这个问题,有什么方法可以将我所有的模拟放在一个单独的文件中,例如我的 fileLoader 模拟并以这种方式注入(inject)它?

我不明白如何注入(inject)它,但它尚未定义。

谢谢

最佳答案

And I can't understand why I am getting the following error:

你定义

fileLoader.getFile("test")
.then(function(res){

所以 getFile() 应该返回一个可以解析的 promise ,但是您返回一个包含两个对象的简单数组

 test.getFile = function(name) {
return [
{
"id": 0,
"name": "Test",
"imgName": "Test.png"
},
{
"id": 1,
"name": "Test1",
"imgName": "Test1.png"
}]

重构一侧。使用延迟或处理数组结果。

关于javascript - AngularJS 单元测试 - 未定义不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28754998/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com