0

我正在尝试在发出 http 请求时测试 http 参数是否正确。

当我做expect(req.request.params.get('action')).toEqual('pause');测试失败时:

预期:“暂停”收到:空

服务

constructor(private _http: HttpClient)

pause(key: string): Observable<ReturnValue> {
    const httpParams = new HttpParams().set('action', 'pause');

    return this._http
        .put<ReturnValue>(`${API.pauseUrl}/${key}`, {
        params: httpParams,
    });
}

测试

let httpMock: HttpTestingController;
let httpClient: HttpClient;
let service: MyService;

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

  httpMock = TestBed.inject(HttpTestingController);
  httpClient = TestBed.inject(HttpClient);
  service = TestBed.inject(MyService);
});

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

describe("WHEN: pause", () => {
  const key = "1q2w3e-4r5t6y";
  const response: ReturnValue = ({
    key,
    status: "paused",
  } as ReturnValue;

  it("THEN: should call http.put with the expected url and params", (done) => {
      service.pause(key).subscribe(() => {
        expect(req.request.method).toBe('PUT');
        expect(req.request.params.get('action')).toEqual('pause');
        expect(req.request.url).toBe(`${PUSH_CORE_API.parcelUrl}/${key}`);
        done();
      });
      const req = httpMock.expectOne({
        method: 'PUT',
        url: `${PUSH_CORE_API.parcelUrl}/${key}`,
      });
      req.flush(response);
  });
});

任何想法为什么会发生这种情况?

我在这个测试中使用 Angular 和 Jest 和 TestBed。

4

2 回答 2

1

您可以像这样进行测试:

it("THEN: should call http.put with the expected url and params", (done) => {
    service.pause(key).subscribe(() => done());

      httpMock
      .expectOne((req: HttpRequest<any>) => {

         expect(rep.url).toBe(`${API.pauseUrl}/${key}`);        
         expect(req.method).toBe('PUT');
         expect(req.params.get('action')).toEqual('pause');
         expect(req.url).toBe(`${API.pauseUrl}/${key}`);

        return true;
      })
      .flush(response);
  });
});

希望对你有帮助

于 2020-04-13T12:37:04.967 回答
1

有类似的问题。希望这对将来的某人有所帮助。

it('THEN: should call http.put with the expected url and params', (done) => {
    service.pause(key).subscribe(() => done());

    const expectedRequest = httpBackend
        .expectOne(r => r.url === `${API.pauseUrl}/${key}`);

    expectedRequest.flush(response);
    expect(expectedRequest.request.url).toBe(`${API.pauseUrl}/${key}`);
    expect(expectedRequest.request.method).toBe('PUT');
    expect(expectedRequest.request.params.get('action')).toEqual('pause');
});
于 2021-09-08T21:02:37.863 回答