嗨,我正在尝试测试自定义类的实例,我在同一个spec文件中进行了多次测试,这就是为什么使用beforeEach
方法,也使用inject
方法来获取所需服务的原因根据我的班级,但是当我运行测试时,变量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();
});
然后我的karma.conf.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']
}
}
});
};
服务的注入是否有可能在它执行后结束?如果显示,如何避免这种行为。
答案 0 :(得分:1)
您没有将提供程序导入测试床:
beforeAll(() => {
TestBed.configureTestingModule({
providers: [...] // <---------- HERE
})
.compileComponents();
});
在那之后,使其变得更简单:使用测试台!它包含依赖项的weekMap:
const myServiceInstance = TestBed.get(MyService);