我正在尝试为我的angular 6应用程序的Login组件编写单元测试。
login.component.ts文件具有以下构造函数
constructor(public global: Globals, private appService: AppService ) {
}这里的Globals是一个普通的ts文件,它有一些跨组件使用的全局函数。AppService是一种服务。
我当前的spec.ts文件
describe('LoginComponent', () => {
let component: LoginComponent;
let fixture: ComponentFixture<LoginComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ LoginComponent ],
imports:[
FormsModule,
ReactiveFormsModule,
],
providers:[
AppService
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(LoginComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});这里的组件实例是未定义的。
谁能指导一下如何为这种情况创建TestBed配置模块,以及如何创建组件的实例?
发布于 2021-10-28 12:40:26
This是学习测试的一个很好的资源。
对于您的情况,我会嘲笑Globals和AppService的公共方法。
describe('LoginComponent', () => {
let component: LoginComponent;
let fixture: ComponentFixture<LoginComponent>;
let mockGlobals: jasmine.SpyObj<Globals>;
let mockAppService: jasmine.SpyObj<AppService>;
beforeEach(async(() => {
mockGlobals = jasmine.createSpyObj('Globals', [/*public methods you want to mock go here as an array of strings */]);
mockAppService = jasmine.createSpyObj('AppService', [/ *public methods you want to mock go here as an array of strings */]);
TestBed.configureTestingModule({
declarations: [ LoginComponent ],
imports:[
FormsModule,
ReactiveFormsModule,
],
providers:[
// provide mocks when component wants actual services
{ provide: Globals, useValue: mockGlobals },
{ provide: AppService, useValue: mockAppService }
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(LoginComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});createSpyObj有很多签名,你可以对它做更多的研究。我给出的链接还展示了如何模拟依赖关系的其他方法。
https://stackoverflow.com/questions/69752497
复制相似问题