首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用jasmine测试promise中的http调用

使用jasmine测试promise中的http调用
EN

Stack Overflow用户
提问于 2020-02-29 01:04:55
回答 1查看 148关注 0票数 0

我正在学习angular和单元测试,似乎无法解决这个问题。也许我做的一切都错了,但我想测试一下是否进行了http调用。

app.service.ts:

代码语言:javascript
运行
复制
transformData(data):Promise<any>{
    return new Promise((resolve, reject) => {
          this.http.post<any>('https://www.example.com',data).subscribe(
        resp => {
         resolve(resp);
         },
        err => {
         reject(err);
         }
      );

       });
    }

我现在的测试是:

代码语言:javascript
运行
复制
fit("should submit data for processing", fakeAsync(() => {

    const service = TestBed.get(AppService);

    let response = {
      processedData: 100
    };

    service
    .transformData({'data':'data'})
    .then(result => {
      expect(result).toEqual(response);
    });

   // Expect a call to this URL
  const req = httpTestingController.expectOne(
  "https://www.example.com/"
    );
  expect(req.request.method).toEqual("POST");
  req.flush(response);
  tick();

  }));

上面写着:

代码语言:javascript
运行
复制
Error: Expected one matching request for criteria "Match URL: https://www.example.com/", found none.
EN

回答 1

Stack Overflow用户

发布于 2020-02-29 01:17:02

我会这样测试它:

代码语言:javascript
运行
复制
fit("should submit data for processing", async(done) => {

    const service = TestBed.get(AppService);

    let response = {
      processedData: 100
    };

    service
    .transformData({'data':'data'})
    .then(result => {
      expect(result).toEqual(response);
      // call done() to tell the test we are done with our assertions
      done();
    });

    // Expect a call to this URL
    const req = httpTestingController.expectOne("https://www.example.com");
    expect(req.request.method).toEqual("POST");
    req.flush(response);
  });
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60456324

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档