功能单元测试

jas*_*130 2 javascript unit-testing function jasmine

我正在为函数 getNextPage() 编写单元测试。我设置了测试:expect(this.anotherService.resources).toEqual(3); 我收到错误:运行测试时预期未定义等于 3。我记录了 anotherService.resources,它在控制台中返回了 3。不知道为什么它不起作用。

测试

describe('Test for someController', function() {
  beforeEach(function() {
    module('someApp');
    return inject(function($injector) {
      var $controller;
      var $q = $injector.get('$q');

      this.rootScope = $injector.get('$rootScope');
      $controller = $injector.get('$controller');
      this.state = $injector.get('$state');
      this.stateParams = {
        id: 1,
      }
      this.location = $injector.get('$location')
      this.timeout = $injector.get('$timeout')
      this.upload = $injector.get('$upload')
      this.someService = {
        getItemList: function(res) {
          var deferred = $q.defer();
          deferred.resolve({
            data: {
              totalRows: 2,
              rows: 3,
            }
          });
          return deferred.promise;
        },
        pages: jasmine.createSpy(),

        memberIds: 1,
        currEng: []
      };
      this.anotherService = {
        resources: {}
      };
      this.scope = this.rootScope.$new();
      this.controller = $controller('someController', {
        '$scope': this.scope,
        '$rootScope': this.rootScope,
        '$state': this.state,
        '$stateParams': this.stateParams,
        '$location': this.location,
        '$timeout': this.timeout,
        '$upload': this.upload,
        'someService': this.someService,
      });
      this.scope.$digest();
    });
  });

  it('should be defined', function() {
    expect(this.controller).toBeDefined();
    expect(this.scope.ss).toEqual(this.someService);
  });

  it('should run the getNextPage function', function() {
    this.scope.getNextPage();
    this.scope.$digest();
    console.log(this.anotherService.resources);        // this is showing as Object {} in terminal
    expect(this.anotherService.resources).toEqual(3);
  });
Run Code Online (Sandbox Code Playgroud)

代码:

someapp.controller('someController', resource);
resource.$inject = ['$scope', '$state', '$stateParams', '$location','$timeout','$upload', 'someService', 'anotherService'];
function resource($scope, $state, $stateParams,$location,$timeout, $upload, someService, anotherService) {

      $scope.fileReaderSupported = window.FileReader != null && (window.FileAPI == null || FileAPI.html5 != false);

      $scope.ss = EsomeService;
      $scope.as = anotherService;
      $scope.getNextPage = getNextPage;


      function getNextPage(options){

        var o = options || {selected:1};
        var start = (o.selected-1)*10 || 0;
        someService.currPage = o.selected;

        someService.getItemList($stateParams.id,'F', start).then(function (res){
          anotherService.resources = res.data.rows;
          console.log(anotherService.resources)   // this shows LOG: 3 in terminal
          someService.numResults = res.data.totalRows;
          someService.pageNumbers = someService.pages(res.data.totalRows,10);
        })
      }
});
Run Code Online (Sandbox Code Playgroud)

tri*_*cot 5

的价值this.anotherService.resources仍然是{}因为在下面的代码在测试then回调执行您的测试运行,以异步方式:

someService.getItemList($stateParams.id,'F', start).then(function (res){
    anotherService.resources = res.data.rows;
    console.log(anotherService.resources)
    someService.numResults = res.data.totalRows;
    someService.pageNumbers = someService.pages(res.data.totalRows,10);
})
Run Code Online (Sandbox Code Playgroud)

虽然在getItemList你同步解决承诺

getItemList: function(res) {
    var deferred = $q.defer();
    deferred.resolve({
        data: {
            totalRows: 2,
            rows: 3,
        }
    });
    return deferred.promise;
},
Run Code Online (Sandbox Code Playgroud)

...实际上,then当您调用deferred.resolve. 当你想到它时,这也没有意义,因为在调用者可以将then调用附加到它之前,必须首先将承诺返回给调用者。相反,它then异步调用回调,即在所有当前执行的代码以空调用堆栈结束之后。这包括您的测试代码!如Angular 文档中所述

then(successCallback, errorCallback, notifyCallback)– 无论承诺何时被解决或将被解决或拒绝,只要结果可用,就会异步then调用成功或错误回调之一。

以及在同一文档中的测试示例中

// Simulate resolving of promise
deferred.resolve(123);
// Note that the 'then' function does not get called synchronously.
// This is because we want the promise API to always be async, whether or not
// it got called synchronously or asynchronously.
Run Code Online (Sandbox Code Playgroud)

如何测试异步代码

首先,你可以让getNextPage返回一个承诺——与返回的承诺相同getItemList

function getNextPage(options){
    var o = options || {selected:1};
    var start = (o.selected-1)*10 || 0;
    someService.currPage = o.selected;
    // store the promise in a variable
    var prom = someService.getItemList($stateParams.id,'F', start);
    prom.then(function (res){
        anotherService.resources = res.data.rows;
        console.log(anotherService.resources)   // this shows LOG: 3 in terminal
        someService.numResults = res.data.totalRows;
        someService.pageNumbers = someService.pages(res.data.totalRows,10);
    });
    return prom; // return that promise
}
Run Code Online (Sandbox Code Playgroud)

然后您可以使用thenon getNextPage(),它将与then附加到它的任何其他回调按顺序执行,因此在then上述代码段中的回调之后。

茉莉的done则可以用来告诉茉莉花测试是异步的,当它已经完成:

// The presence of the `done` parameter indicates to Jasmine that 
// the test is asynchronous 
it('should run the getNextPage function', function(done) { 
    this.scope.getNextPage().then(function () {
        this.scope.$digest();
        console.log(this.anotherService.resources);
        expect(this.anotherService.resources).toEqual(3);
        done(); // indicate to Jasmine that the asynchronous test has completed
    });
});
Run Code Online (Sandbox Code Playgroud)