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

AngluarJS Unit Test - Undefined is not a function

本文关键字:函数 未定义 单元测试 AngluarJS      更新时间:2024-06-20

我正在努力学习如何在angular中进行单元测试。单元测试我的控制器,然后开始我的服务。

我从一个基本的测试开始。

控制器代码:

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"不是函数(正在求值'fileLoader.getFile("test").then')未定义的

一旦解决了这个问题,我有没有办法把所有的mock放在一个单独的文件中,比如我的fileLoader mock,然后用这种方式注入它?

我不明白我是怎么注射的,但它还没有定义。

感谢

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

你定义了

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

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