【发布时间】:2023-04-09 23:40:02
【问题描述】:
我对单元测试相当陌生。我正在构建一个 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);
});
});
这是怎么回事?
【问题讨论】:
-
能不能把myComponent的代码也放上来。
-
@AnoopRajasekharaWarrier sView = false;几乎是唯一发生的事情。
-
只是为了确认一切是否正常,你可以试试吗('should create', () => { expect(component).toBeTruthy(); });在你拥有的 it() 语句之前。
-
通过了吗? it('应该创建', () => { expect(component).toBeTruthy(); });
-
相同的 http 问题和“预期未定义为真。”
标签: angular typescript jasmine karma-jasmine