gpt4 book ai didi

javascript - 无法读取 Angular 中未定义的属性 'getData'

转载 作者:行者123 更新时间:2023-12-03 02:04:40 26 4
gpt4 key购买 nike

您能告诉我为什么会收到此错误无法读取未定义的属性“getData”我正在尝试测试我的服务,当我尝试运行测试时它给出了上述错误这是我的代码 https://stackblitz.com/edit/angular-testing-w9towo?file=app%2Fapp.service.spec.ts

     import { TestBed, ComponentFixture, async, inject } from '@angular/core/testing';
import {HttpClientTestingModule, HttpTestingController} from '@angular/common/http/testing';
import {Posts} from './post.interface';

import { AppService } from './app.service';

describe('AppService', () => {
let service:AppService,
httpMock:HttpTestingController;
beforeEach(() => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [AppService]

}).compileComponents();
service =TestBed.get(AppService);
httpMock =TestBed.get(HttpTestingController);

}));

afterEach(()=>{
httpMock.verify();
})
})


describe('Service is truty', () => {
it('should return an Observable<User[]>', () => {
const dummyUsers :Posts[]= [{
userId: 10,
id: 10,
title: 'post',
body: 'post'
}];

service.getData().subscribe(users => {
console.log(users)
expect(users.length).toBe(1);
expect(users).toEqual(dummyUsers);
});

const req= httpMock.expectOne('https://jsonplaceholder.typicode.com/posts')
expect(req.method).toBe('GET');
req.flush(dummyUsers);
});

})
})

尝试更多后,我得到无法读取未定义的属性“getData”

enter image description here

最佳答案

为什么使用嵌套的 beforeEach()compileComponents()?您的 beforeEach() 语句应如下所示:

beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [AppService]
});

service = TestBed.get(AppService);
httpMock = TestBed.get(HttpTestingController);
});

关于javascript - 无法读取 Angular 中未定义的属性 'getData',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49848358/

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