【问题标题】:Cannot set property 'http' of undefined - Angular Unit testing无法设置未定义的属性“http”-Angular 单元测试
【发布时间】: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


【解决方案1】:

试试下面的代码:

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();
});
});

【讨论】:

  • myComponent 应该是你的组件类名,MyServieMock 是模拟服务,myService 是你的服务类名
  • 可能有拼写错误。请给出您的实际班级名称
  • 如果我拿走提供者,http 错误就会消失,这意味着什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-04-04
  • 1970-01-01
  • 2020-02-21
  • 2019-01-08
  • 2015-12-07
  • 2018-12-23
  • 2021-01-22
相关资源
最近更新 更多