无法设置未定义的 属性 'http' - Angular 单元测试
Cannot set property 'http' of undefined - Angular Unit testing
我对单元测试还很陌生。我正在构建一个 Angular 组件,我的测试套件是 Jasmine/Karma.
我的第一个测试抱怨两个问题,我只是想测试一个初始化的变量值:
TypeError: Cannot set property 'http' of undefined
TypeError: Cannot read property 'isView' of undefined
代码非常简单所以想知道为什么我会收到这些错误?
myComponent.ts
sView = false;
myComponent.spec.ts
describe('myComponent', () => {
let component: myComponent;
let fixture: ComponentFixture<myComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
schemas: [NO_ERRORS_SCHEMA],
declarations: [myComponent],
imports: [HttpClientTestingModule],
providers: [
{
provide: myService,
useFactory: myServiceMock
}
]
});
fixture = TestBed.createComponent(myComponent);
component = fixture.componentInstance;
});
it('isView defaults to: false', () => {
expect(component.isView).toEqual(false);
});
});
这是怎么回事?
试试下面的代码:
describe('myComponent', () => {
component: myComponent;
let fixture: ComponentFixture<myComponent>;
let myServiceMock: MyServiceMock;
beforeEach(async(() => {
myServiceMock = new MyServiceMock();
TestBed.configureTestingModule({
declarations: [myComponent],
providers: [
{ provide: myService, useValue: myServiceMock }
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(myComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
beforeEach(() => {
component.ngOnInit();
})
it('should create the app component', () => {
expect(component).toBeTruthy();
});
});
我对单元测试还很陌生。我正在构建一个 Angular 组件,我的测试套件是 Jasmine/Karma.
我的第一个测试抱怨两个问题,我只是想测试一个初始化的变量值:
TypeError: Cannot set property 'http' of undefined
TypeError: Cannot read property 'isView' of undefined
代码非常简单所以想知道为什么我会收到这些错误?
myComponent.ts
sView = false;
myComponent.spec.ts
describe('myComponent', () => {
let component: myComponent;
let fixture: ComponentFixture<myComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
schemas: [NO_ERRORS_SCHEMA],
declarations: [myComponent],
imports: [HttpClientTestingModule],
providers: [
{
provide: myService,
useFactory: myServiceMock
}
]
});
fixture = TestBed.createComponent(myComponent);
component = fixture.componentInstance;
});
it('isView defaults to: false', () => {
expect(component.isView).toEqual(false);
});
});
这是怎么回事?
试试下面的代码:
describe('myComponent', () => {
component: myComponent;
let fixture: ComponentFixture<myComponent>;
let myServiceMock: MyServiceMock;
beforeEach(async(() => {
myServiceMock = new MyServiceMock();
TestBed.configureTestingModule({
declarations: [myComponent],
providers: [
{ provide: myService, useValue: myServiceMock }
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(myComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
beforeEach(() => {
component.ngOnInit();
})
it('should create the app component', () => {
expect(component).toBeTruthy();
});
});