繁体   English   中英

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

[英]AngluarJS Unit Test - Undefined is not a function

我正在尝试学习如何在角度范围内进行单元测试。 对我的控制器进行单元测试,然后从我的服务开始。

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

控制器代码:

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:“未定义”不是函数(未定义(评估“ fileLoader.getFile(“ test”)。then”))函数

一旦解决,有什么办法可以将所有模拟放置在单独的文件中,例如,我的fileLoader模拟并以这种方式注入吗?

我不知道如何注射,但尚未定义。

谢谢

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

你定义

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"
   }]

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM