角度单位测试 - 间谍必须在之前的函数或规范中创建

时间:2017-07-11 19:15:37

标签: javascript angularjs unit-testing

我的单元测试出现以下错误。如果需要,我可以发布dashboard.service.js文件。 DashboardService.getHostDetails()返回我正在尝试处理的promise,因此我尝试使用spyOn()。

Error: Spies must be created in a before function or a spec

dashboard.spec.js

import DashboardModule from './dashboard.module'
import DashboardService from './dashboard.service'

let dashboardService,
    _$translateProvider,
    _$q;

describe('DashboardService', () => {
  beforeEach(angular.mock.module(DashboardModule));

  beforeEach(() => {
    angular.mock.module({
      $translateProvider: jasmine.createSpyObj('$translateProvider',
        ['translations', 'preferredLanguage']
      ),
      $translate: jasmine.createSpyObj('$translate',
        ['use']
      )
    });
  })

  beforeEach(inject(($translateProvider, $q, DashboardService) => {
    _$translateProvider = $translateProvider;
    _$q = $q;

    dashboardService = DashboardService;
  }));

  beforeEach(() => {
    _$translateProvider.translations('en', {});
    _$translateProvider.preferredLanguage('en');

    const promise = { then: jasmine.createSpy() };
    spyOn(dashboardService, 'getHostDetails').and.andReturn(promise);
  });

  it('should load the host information', () => {
    const hostDetails = dashboardService.getHostDetails();
    console.log(hostDetails);
    hostDetails.then((res) => {
      console.log(res);
    });
  });
});

1 个答案:

答案 0 :(得分:0)

所以问题是摩卡,柴和茉莉都被使用和冲突。现在只使用茉莉花解决了这个问题。结果更新了我的karma.conf.js