如何在引导角度应用程序之前模拟AJAX调用

时间:2016-09-13 15:51:45

标签: angularjs jasmine karma-runner karma-jasmine

我有一个角度应用程序,在引导之前执行2个ajax请求。第一次调用获取一个JSON文件,其中包含第二次调用的配置(到真正的后端)。这两个请求对于应用程序的配置至关重要。他们都设置.constant()以供初始应用.run()阶段使用。

现在我想摆脱我的Karma控制台中的错误,让我知道这些调用返回的数据是undefined。我如何模仿它们以便Karma实际上不会尝试执行这些调用?

这是我到目前为止所做的:

app.js

// imports before and "requires" array for modules dependencies

const app = angular
  .module('app-gouvernementales', requires)
  .config(appConfig)
  .run(appRun)
  .component('appGouvernementales', AppComponent);

getConfig()
  .then((config) => {
    angular.module('app-gouvernementales')
      .constant('APP_SETTINGS', appConstant(config));

    return { url: `${config.protocol}://${config.host}`, uid: config.shibbolethUid };
  })
  .then(data => getUser(data.url, data.uid))
  .catch((err) => {
    console.log(err);
    document.location.href = '/erreur/role';
  })
  .then((_user_) => {
    const user = _user_.data;

    angular.module('app-gouvernementales')
      .constant('USER', user);
  })
  .then(() => {
    angular.bootstrap(document, ['app-gouvernementales']);
  });

function getConfig() {
  const initInjector = angular.injector(['ng']);
  const $http = initInjector.get('$http');

  return $http.get('/gouvernementales/app-gouvernementales.config.json')
    .then(response => response.data);
}

function getUser(url, uid) {
  const initInjector = angular.injector(['ng']);
  const $http = initInjector.get('$http');

  return $http.get(`${url}/roles`, { withCredentials: true, headers: { 'X-uid': uid } });
}

jasmine.spec

describe('Créer', () => {
  let $httpBackend;
  let $componentController;
  let component;
  let scope;
  let createComponent;

  const userData = {
    centreArchive: {
      adresse: 'Campus de l\'Université Laval, C.P. 10450 succ. Sainte-Foy',
      code: '03Q',
      codePostal: 'G1V 4N1',
      indActif: true,
      nom: 'BAnQ Québec',
      telecopieur: '111-222-3333',
      telephone: '111-222-3333',
      typeCentre: 'BANQ',
      ville: 'Québec',
    },
    codeUsager: '01263634',
    courriel: 'john.doe@email.qc.ca',
    idOrganisme: 30888,
    indExterne: true,
    nom: 'John',
    prenom: 'Doe',
    roles: [
      'ARCHIVISTE_ORGANISME',
    ],
  };

  const appSettings = {
    baseUrl: '/gouvernementales',
    shibbolethUid: '01263935',
    protocol: 'https',
    host: 'dev-api-pistard.banq.qc.ca/pistard/service',
    port: 3000,
    apiLogoutUrl: 'https://acpt-www.banq.qc.ca/idp/logout_banq.jsp',
    apiLoginUrl: 'https://dev-pistard.banq.qc.ca',
  };

  beforeEach(() => {
    angular.mock.module('app-gouvernementales', ($provide) => {
      $provide.constant('APP_SETTINGS', appSettings);
      $provide.constant('USER', userData);
    });

    angular.mock.inject(($rootScope, _$componentController_, $injector) => {
      $httpBackend = $injector.get('$httpBackend');

      $httpBackend
        .whenGET('/gouvernementales/app-gouvernementales.config.json')
        .respond(appSettings);

      $httpBackend
        .whenGET('https://dev-api-pistard.banq.qc.ca/pistard/service/roles')
        .respond(userData);

      scope = $rootScope.$new();
      $componentController = _$componentController_;

      createComponent = () => $componentController('appGouvernementales', { $scope: scope });
    });
  });

  afterEach(function() {
   $httpBackend.verifyNoOutstandingExpectation();
   $httpBackend.verifyNoOutstandingRequest();
 });

  it('should be defined', () => {
    expect(component).not.toBe(null);
  });
});

Karma堆栈跟踪(仅从第一个错误提供):

第一行是对JSON文件的第一个AJAX请求的404。

如果你看一下Error: undefined is not an object (evaluating '_user_.data')行,这就是第二个ajax请求响应中的错误。

13 09 2016 11:37:38.074:WARN [web-server]: 404: /gouvernementales/app-gouvernementales.config.json
  Créer
    ✔ should be defined
Missing error handler on `socket`.
Error: Karma: Tests Failed
    at null.<anonymous> (/Users/justinledoux/dev/banq/trunk/gulp/tasks/unit.js:37:15)
    at emitTwo (events.js:92:20)
    at emit (events.js:172:7)
    at emitRunCompleteIfAllBrowsersDone (/Users/justinledoux/dev/banq/trunk/node_modules/karma/lib/server.js:294:12)
    at null.<anonymous> (/Users/justinledoux/dev/banq/trunk/node_modules/karma/lib/server.js:325:7)
    at emitOne (events.js:77:13)
    at emit (events.js:169:7)
    at null.<anonymous> (/Users/justinledoux/dev/banq/trunk/node_modules/karma/lib/server.js:308:12)
    at emitTwo (events.js:92:20)
    at emit (events.js:172:7)
    at onComplete (/Users/justinledoux/dev/banq/trunk/node_modules/karma/lib/browser.js:143:13)
    at Socket.<anonymous> (/Users/justinledoux/dev/banq/trunk/node_modules/karma/lib/events.js:13:22)
    at emitTwo (events.js:92:20)
    at Socket.emit (events.js:172:7)
    at Socket.onevent (/Users/justinledoux/dev/banq/trunk/node_modules/karma/node_modules/socket.io/lib/socket.js:335:8)
    at Socket.onpacket (/Users/justinledoux/dev/banq/trunk/node_modules/karma/node_modules/socket.io/lib/socket.js:295:12)
13 09 2016 11:37:38.082:DEBUG [phantomjs.launcher]: [object Object]
Error: undefined is not an object (evaluating '_user_.data')
http://localhost:3003/absolute/var/folders/84/crwsxkwj68q984lrslg4zg2c0000gn/T/775f2191098ceb34160b59835abb93a7.browserify?ef7b2c96fcbcc4e558f82ad088601011cba2cb1e:272:20
http://localhost:3003/base/build/gouvernementales/js/gouvernementales-libs.js?2757b916663597c2f58efbc3773f02a2cb0bb822:135:21
$eval@http://localhost:3003/base/build/gouvernementales/js/gouvernementales-libs.js?2757b916663597c2f58efbc3773f02a2cb0bb822:149:347
$digest@http://localhost:3003/base/build/gouvernementales/js/gouvernementales-libs.js?2757b916663597c2f58efbc3773f02a2cb0bb822:146:425
$apply@http://localhost:3003/base/build/gouvernementales/js/gouvernementales-libs.js?2757b916663597c2f58efbc3773f02a2cb0bb822:150:120
l@http://localhost:3003/base/build/gouvernementales/js/gouvernementales-libs.js?2757b916663597c2f58efbc3773f02a2cb0bb822:101:373
J@http://localhost:3003/base/build/gouvernementales/js/gouvernementales-libs.js?2757b916663597c2f58efbc3773f02a2cb0bb822:106:35
e@http://localhost:3003/base/build/gouvernementales/js/gouvernementales-libs.js?2757b916663597c2f58efbc3773f02a2cb0bb822:107:56

  :0 in apply

13 09 2016 11:37:38.086:DEBUG [launcher]: Process PhantomJS exited with code 0
13 09 2016 11:37:38.087:DEBUG [temp-dir]: Cleaning temp dir /var/folders/84/crwsxkwj68q984lrslg4zg2c0000gn/T/karma-29433906
13 09 2016 11:37:38.090:DEBUG [launcher]: Finished all browsers
13 09 2016 11:37:48.078:WARN [PhantomJS 2.1.1 (Mac OS X 0.0.0)]: Disconnected (1 times), because no message in 10000 ms.
[11:37:48] Karma Run Failed: undefined
13 09 2016 11:37:48.082:ERROR [karma]: Disconnected, because no message in 10000 ms.
13 09 2016 11:37:48.082:DEBUG [launcher]: Disconnecting all browsers
13 09 2016 11:37:48.082:DEBUG [framework.browserify]: cleaning up

0 个答案:

没有答案