gpt4 book ai didi

javascript - Angular 4 单元测试出现错误 - 失败 : Cannot read property 'map' of undefined

转载 作者:行者123 更新时间:2023-12-03 02:29:07 24 4
gpt4 key购买 nike

我试图在 Angular 4 单元测试中取得成功,但出现了不同的错误,我收到错误 Failed: Cannot read property 'map' of undefined .

我仅在服务文件上使用 .map(),但我不知道为什么显示此错误

我想知道如何才能在这次测试中取得成功,如果,我的方法正确吗?

看看我的代码:

我的规范

import { TestBed, async, inject } from '@angular/core/testing';
import { HttpModule } from '@angular/http';
import { of } from 'rxjs/observable/of';
import { fileX } from '../../../models/fileX';
import { fileXService } from '../../../services/fileX.service';
import { fileYfileXComponent } from './fileY-fileX.component';
import { dataService } from '../../../services/data.service';
import { ComponentFixture } from '@angular/core/testing';

describe('fileYfileXComponent', () => {
let fileXService;
let myComponent;
let fixture: any;
let element;
let mockHttp: httpClient;

beforeEach(async(() => {
mockHttp = jasmine.createSpyObj('http', ['get']);

TestBed.configureTestingModule({
declarations: [fileYfileXComponent],
providers: [
fileXService,
dataService,
{ provide: Http, useValue: mockHttp }
],
imports: [HttpModule]
}).compileComponents();
}));

beforeEach(inject([fileXService], s => {
fileXService = s;
fixture = TestBed.createComponent(fileYfileXComponent);
myComponent = fixture.componentInstance;
element = fixture.nativeElement;
}));

it(
'should get values',
async(() => {
const response: fileX[] = [];

spyOn(fileXService, 'method1').and.returnValue(of(response));

myComponent.searchdatafileX();

fixture.detectChanges();

expect(myComponent.datafileX).toEqual(response);
})
);
});

最佳答案

目前,您正在正确模拟 HubWrapperComponent,这样它就不会在您每次调用 get 时调用您的后端。为了使其正常工作,您需要使用 Jasmine 的 Spy 实用程序 returnValue 来告诉测试在调用 http.get 时应返回什么内容。目前,尚未指定,因此 map 正在 undefined 上调用。

在您的规范文件中,在以下行之后:

mockHub = jasmine.createSpyObj('hubWrapperComponent', ['get']);

添加这一行:

mockHub.get.and.returnValue(// your test response);

根据服务中的代码,我的假设是您期望从 get 方法获得 Observable,因此您的 returnValue 调用将如下所示:

mockHub.get.and.returnValue(Observable.of(
{
json: () => {
return // object with properties you want to test
}
}
)
);

有关此方法的更多信息,请参见:https://jasmine.github.io/api/2.7/Spy_and.html

关于javascript - Angular 4 单元测试出现错误 - 失败 : Cannot read property 'map' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48811045/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com