angular - 如何在 Angular 7 的 beforeEach Karma/Jasmine 测试中将服务注入自定义类?
问题描述
嗨我正在尝试测试自定义类实例化,我在同一个规范文件中有几个测试,这就是为什么使用该beforeEach
方法,我也使用inject
方法来获取我的类所需的服务,但是当我运行测试时,varappointmentCreationVehicle
是未定义这是我的代码:
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']
}
}
});
};
有可能在它执行之后服务的注入结束吗?如果我展示,我该如何避免这种行为。
解决方案
您没有将提供程序导入您的测试平台:
beforeAll(() => {
TestBed.configureTestingModule({
providers: [...] // <---------- HERE
})
.compileComponents();
});
之后,让它更简单:使用测试平台!它包含依赖项的 weekMap :
const myServiceInstance = TestBed.get(MyService);
推荐阅读
- azure - 将 Azure AppService 部署到 Url:404 + 没有工作人员分配给应用服务计划。该网站无法处理任何请求
- asp.net - 扩展现有的 ABP 控制器
- heroku - 是否可以将原始 Java Web 应用程序部署到 Heroku?
- python - 用字母和数字在python中对表格进行排序
- python - 为 Metashape 中的密集云点分配自定义置信度
- reactjs - 从 props 数组 no-unused-vars 导入图像
- caching - GITLAB CI/CD 使用缓存或工件提高流水线速度?
- reactjs - 等待 localStorage 更新,然后在 useEffect 上调度 fetch
- excel - MS Excel:在第一个测试和修剪实例之后查找第一个文本实例
- spring - 春季批处理 - 作业在 STARDED 状态下仍然被阻止