如何在无后端应用程序中使用单元测试?

时间:2016-03-15 09:05:44

标签: angularjs unit-testing mocking

我使用单元测试创​​建无后端应用程序,测试是一个http get调用,我的问题是当我在主应用程序中删除ngMockE2E模块并在app.run()中伪造后端http get处理程序时工作正常但是当在app.run()中添加添加ngMockE2E和假后端http get处理程序然后运行测试时,将出现此错误:

Error: No pending request to flush !
    createHttpBackendMock/$httpBackend.flush@C:/app-server-ui/libs/angular/angular-mocks/angular-mocks.js:1779:1
    @C:/app-server-ui/test/signin.controller.test.js:35:7
    invoke@C:/app-server-ui/libs/angular/angular/angular.js:4523:14
    workFn@C:/app-server-ui/libs/angular/angular-mocks/angular-mocks.js:2810:11
    angular.mock.inject@C:/app-server-ui/libs/angular/angular-mocks/angular-mocks.js:2778:25
    @C:/app-server-ui/test/signin.controller.test.js:17:35
    @C:/app-server-ui/test/signin.controller.test.js:16:3
    @C:/app-server-ui/test/signin.controller.test.js:4:1

我的测试文件是:

describe("SigninCtrl", function () {

  var $httpBackend, $controller, $rootScope, createController, authRequestHandler;
  beforeEach(module("app"));

  beforeEach(inject(function ($injector) {
    $controller = $injector.get("$controller");
    $httpBackend = $injector.get("$httpBackend");
    authRequestHandler = $httpBackend.when("GET", "/signin")
      .respond({username: "admin", password: "admin"});
  }));

  describe("auth user", function () {
    it("user pass must be admin", inject(function ($http) {

      var $scope = {};

      /* Code Under Test */
      var controller = $controller("SigninCtrl", {$scope: $scope});
      /* End */
      $http.get("/signin.py")
        .success(function (data) {
          $scope.user = data.user;
        });
      $httpBackend.whenGET('/signin.py').respond({
        "user": {
          "username": "admin",
          "password": "admin"
        }
      });

      $httpBackend.flush();
      expect($scope.user).toEqual({username: "admin", password: "admin"});
    }));
  })
});

我的app运行功能是:

angular
    .module('app')
    .run(runBlock)
    .config(config);
  runBlock.$inject = ['$rootScope', '$state', '$stateParams', '$httpBackend'];
  function runBlock($rootScope, $state, $stateParams, $httpBackend) {
    $rootScope.$state = $state;
    $rootScope.$stateParams = $stateParams;
    $httpBackend.whenGET(/(\.html|\.svg)/).passThrough();
    $httpBackend.whenGET('/signin.py').respond({
      "user": {
        "username": "admin",
        "password": "admin"
      }
    })
  }

0 个答案:

没有答案