嗨,我正在尝试测试自定义类实例化,我在同一个规范文件中进行了多个测试,这就是为什么使用 beforeEach
方法,我也使用inject
方法来获取我的类所需的服务,但是当我运行测试时,var appointmentCreationVehicle
未定义这是我的代码:
describe('AppointmentCreationVehicle', () => {
let appointmentCreationVehicle: AppointmentCreationVehicle;
beforeAll(() => {
TestBed.configureTestingModule({
imports: [AppModule]
})
.compileComponents();
});
beforeEach(
inject([AppointmentCreationVehicle], (vehicleRestService: VehicleRestService) => {
appointmentCreationVehicle = new AppointmentCreationVehicle(vehicleRestService);
})
);
it('should create an instance',() => {
expect(appointmentCreationVehicle).toBeTruthy();
});
那么我的业力.js看起来像这样:
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-firefox-launcher'),
require('karma-mocha-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
],
client: {
clearContext: false, // leave Jasmine Spec Runner output visible in browser
jasmine: {
random: false
},
captureConsole: true,
mocha: {
bail: true
}
},
reporters: ['mocha'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['HeadlessFirefox'],
singleRun: true,
customLaunchers: {
HeadlessFirefox: {
base: 'Firefox',
flags: ['-headless']
},
ChromeDebugging: {
base: 'Chrome',
flags: ['--remote-debugging-port=9876']
}
}
});
};
是否有可能在执行后结束服务的注入?如果我展示,我怎样才能避免这种行为。
您没有将提供程序导入测试平台:
beforeAll(() => {
TestBed.configureTestingModule({
providers: [...] // <---------- HERE
})
.compileComponents();
});
之后,让它更简单:使用测试平台!它包含一个依赖关系的一周映射:
const myServiceInstance = TestBed.get(MyService);