如何使用AngularJS服务依赖项对Angular服务进行单元测试

时间:2018-11-08 14:25:48

标签: angularjs angular unit-testing migration angular7

我正在尝试将angular js服务迁移到新的angular 7应用程序。但是,每个服务都依赖于其他angularjs服务,因此我无法在继续创建新功能的同时将它们全部转换。如何在单元测试中注入angular js服务,以便可以测试Angular 7服务?

tests.ts //测试条目文件

import 'core-js/es6';
import 'reflect-metadata';
import 'zone.js/dist/zone';
import 'zone.js/dist/long-stack-trace-zone';
import 'zone.js/dist/proxy';
import 'zone.js/dist/sync-test';
import 'zone.js/dist/jasmine-patch';
import 'zone.js/dist/async-test';
import 'zone.js/dist/fake-async-test';

import { getTestBed } from '@angular/core/testing';
import {
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';

declare const require: any;

// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting()
);

// Then we find all the tests.
const context = require.context('./', true, /\.spec\.ts$/);

// And load the modules.
context.keys().map(context);

TestService.ts

import { UpgradeModule } from '@angular/upgrade/static';
import { CHECKOUT_SERVICE } from '../../../../ajs-upgraded-providers';

@Injectable({
 providedIn: 'root'
})
export class TestService {
   let checkout: any;
   constructor(@Inject(CHECKOUT_SERVICE) private checkoutService: any){
     this.checkout = checkoutService;
   }
}

TestService.spec.ts

import { TestBed } from '@angular/core/testing';
import { TestingService } from './testing-service';
import { CheckoutServiceProvider } from 'ajs-upgraded-provider.ts'

describe('testing service with an injected AJS service', () => {
  let service: TestingService;
  TestBed.configureTestingModule({
  providers:[
    TestService,
    CheckoutServiceProvider
  ],
  imports:[ upgradeModule ]
 });
  service = TestBed.get(TestingService);
})
  it('instance should be created', () => {
    expect(expect(service).toBeTruthy();
  })
})

运行此单元测试时,出现以下错误:

Error: Trying to get the AngularJS injector before it being set.

2 个答案:

答案 0 :(得分:0)

尝试通过这种方式进行操作:

class MockConfigurationService {

}
class SomeMockCheckOutService {

}

// Configure the component with another set of Providers
TestBed.overrideComponent(
  TestService,
  { 
    set: { 
      providers: [
        {
          provide: CHECKOUT_SERVICE, 
          useClass: MockConfigurationService
        },
        {
          provide: CheckoutService, 
          useClass: SomeMockCheckOutService
        }
     ] 
   } 
  }
);

答案 1 :(得分:0)

如果您不想使用模拟,这对我有用:

将此添加到您的beforeEachMethod

const upgrade = TestBed.get(UpgradeModule) as UpgradeModule;
upgrade.bootstrap(document);
const serviceWhichReliesonInjector = 

之后,我可以通过以下方式简单地访问服务

TestBed.get(ServiceWhichReliesonInjector)