我正在尝试将AngularJS服务迁移到新的Angular 7应用程序中。然而,每个服务都有许多依赖于其他AngularJS服务,我无法在继续创建新功能的同时全部转换它们。如何在单元测试中注入AngularJS服务,以便可以测试我的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.