Jasmine服务的单元测试不返回数据

Jasmine服务的单元测试不返回数据,jasmine,karma-runner,angular9,Jasmine,Karma Runner,Angular9,伙计们!我是一个新的测试人员,一直在处理这个问题。我正在尝试为我的服务编写单元测试,它从服务器获取数据。经典案例: import {TestBed} from '@angular/core/testing'; import {ShiftsService} from "./shifts.service"; import {Shift} from "../shift/shift"; describe('ShiftService - testing HTTP request method getSh

伙计们!我是一个新的测试人员,一直在处理这个问题。我正在尝试为我的服务编写单元测试,它从服务器获取数据。经典案例:

import {TestBed} from '@angular/core/testing';
import {ShiftsService} from "./shifts.service";
import {Shift} from "../shift/shift";

describe('ShiftService - testing HTTP request method getShifts()', () => {
  let httpTestingController: HttpTestingController;

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

  it('can test HttpClient.get', () => {
    let shifts = new Array<Shift>();
    let shiftsService;
    let calendarMonth = new Date().getMonth()+2;
    let calendarYear  = new Date().getFullYear();
    shiftsService = TestBed.inject(ShiftsService);
    httpTestingController = TestBed.inject(HttpTestingController);
    shiftsService.getShifts(calendarYear, calendarMonth).subscribe(response => {expect(response).toBe(response.length);
    console.log(response);
    });

    let apiRequest:string = '/api/shifts?year='.concat(calendarYear.toString()).concat('&month=').concat(calendarMonth.toString());
    const req = httpTestingController.expectOne(apiRequest);
    console.log(apiRequest);
    expect(req.request.method).toBe('GET');

    req.flush(shifts);
  });

  afterEach(() => httpTestingController.verify());
});
从'@angular/core/testing'导入{TestBed};
从“/shifts.service”导入{ShiftsService};
从“./Shift/Shift”导入{Shift};
description('ShiftService-测试HTTP请求方法getShifts()',()=>{
设httpTestingController:httpTestingController;
在每个之前(()=>{
TestBed.configureTestingModule({
导入:[HttpClientTestingModule],
提供者:[移动服务]
});
});
它('可以测试HttpClient.get',()=>{
让移位=新数组();
让我们一起去服务;
让calendarMonth=新日期().getMonth()+2;
让calendarYear=新日期().getFullYear();
shiftsService=TestBed.inject(shiftsService);
httpTestingController=TestBed.inject(httpTestingController);
GetShift(calendarYear,calendarMonth).subscribe(响应=>{expect(响应).toBe(响应.length));
控制台日志(响应);
});
let-apirest:string='/api/shifts?year='.concat(calendarYear.toString()).concat('&month=').concat(calendarMonth.toString());
const req=httpTestingController.expectOne(apiRequest);
console.log(apirest);
expect(req.request.method).toBe('GET');
要求冲洗(班次);
});
每次之后(()=>httpTestingController.verify());
});
我在服务文件中的方法如下所示:

getShifts (year: number, month: number): Observable<Shift[]> {
    let params = new HttpParams();
    params = params.append('year', year.toString());
    params = params.append('month', month.toString());

    return this.http.get<Shift[]>(this.shiftsUrl, { params: params })
      .pipe(tap((shifts) => shifts),
        catchError((err) => this.handleError(err)))
  }
getshift(年:数,月:数):可观察{
设params=newhttpparams();
params=params.append('year',year.toString());
params=params.append('month',month.toString());
返回this.http.get(this.shiftsUrl,{params:params})
.管道(水龙头((班次)=>班次),
catchError((err)=>this.handleError(err)))
}

我得到了错误:错误:预期[]为0。当我打印出响应时,我得到的变量是空的!但我确信这种方法很有效!它在我的应用程序中运行良好!你能帮我解决这个问题吗?如何更正我的测试方法来测试服务?

最后,您正在执行
req.flush(shifts)
shifts=newarray()本质上是
[]
。刷新是您希望HTTP get请求响应的内容,在本例中,它是一个空数组

在订阅中,您正在断言
response
[]
)等于
response.length
,即
0

试试这个:

it('can test HttpClient.get', (done) => { // add done callback to be able to call it in the subscribe
    let shifts = new Array<Shift>();
    let shiftsService;
    let calendarMonth = new Date().getMonth()+2;
    let calendarYear  = new Date().getFullYear();
    shiftsService = TestBed.inject(ShiftsService);
    httpTestingController = TestBed.inject(HttpTestingController);
    shiftsService.getShifts(calendarYear, calendarMonth).subscribe(response => {
       // we have to use toEqual because toBe does a deep assertion
       // but the array to compare to is in a different location in memory so 
       // toBe would fail
       expect(response).toEqual([]);
       console.log(response);
       // call done to tell the unit test you are done with this test
       done();
    });

    let apiRequest:string = '/api/shifts?year='.concat(calendarYear.toString()).concat('&month=').concat(calendarMonth.toString());
    const req = httpTestingController.expectOne(apiRequest);
    console.log(apiRequest);
    expect(req.request.method).toBe('GET');

    shifts.push(/* push a shift here */) // change the shifts array to what you want the server to respond with 
    req.flush(shifts);
  });
it('can test HttpClient.get',(done)=>{//add done回调,以便能够在订阅中调用它
让移位=新数组();
让我们一起去服务;
让calendarMonth=新日期().getMonth()+2;
让calendarYear=新日期().getFullYear();
shiftsService=TestBed.inject(shiftsService);
httpTestingController=TestBed.inject(httpTestingController);
shiftsService.GetShift(日历年、日历月)。订阅(响应=>{
//我们必须使用toEqual,因为toBe做了一个深刻的断言
//但是要比较的数组在内存中的位置不同,所以
//托比会失败
期望(回应)。托夸尔([]);
控制台日志(响应);
//调用done告诉单元测试您已完成此测试
完成();
});
let-apirest:string='/api/shifts?year='.concat(calendarYear.toString()).concat('&month=').concat(calendarMonth.toString());
const req=httpTestingController.expectOne(apiRequest);
console.log(apirest);
expect(req.request.method).toBe('GET');
shifts.push(/*在此处推一个shift*/)//将shifts数组更改为您希望服务器响应的值
要求冲洗(班次);
});

谢谢你的回答!错误消失了,但我仍然无法从服务器获取数据!回答是空的!Change
转换为您想要的响应。我们正在用
req.flush(shifts)
模拟响应,因此无论我们刷新什么,都将是响应。我想从服务器获取移位数组。。。我不明白它必须如何改变?当进行单元测试时,我们实际上不进行HTTP调用。我们嘲笑他们。当我们
req.flush
时,我们向http调用发送模拟响应。因此,如果需要移位数组,请在
req.flush
中发送移位数组。我编辑了我的答案。