【问题标题】:How to store the result of an async method in a class property?如何将异步方法的结果存储在类属性中?
【发布时间】:2019-06-03 21:33:41
【问题描述】:

我正在尝试使用具有单个异步方法的类从网页中获取 HTML。我使用 Typescript 3.4.3,request-promise 4.2.4。

import * as rp from 'request-promise';

class HtmlFetcher {

  public uri: string;
  public html: string;

  public constructor(uri: string) {
    this.uri = uri;
  }

  public async fetch() {
    await rp(this.uri).then((html) => {
      this.html = html;
    }).catch((error) => {
      throw new Error('Unable to fetch the HTML page');
    });
  }

}

export { HtmlFetcher };

我使用以下代码使用 Jest 24.8.0 测试我的课程。第 6 行的地址仅用于测试目的,我也尝试了不同的 URI。

import { HtmlFetcher } from './htmlFetcher.service';

describe('Fetch HTML', () => {

  it('should fetch the HTMl at the given link', () => {
    const uri = 'http://help.websiteos.com/websiteos/example_of_a_simple_html_page.htm';
    const fetcher = new HtmlFetcher(uri);
    fetcher.fetch();

    expect(fetcher.html).toBeDefined();
  });

});

我希望html 属性包含在调用 fetch() 方法后从给定地址获取的 HTML 字符串。但是,测试代码失败,并记录 fetcher.htmlundefined。 Typescript、Jest 和 request-promise 文档没有提供任何帮助。我做错了什么?

【问题讨论】:

  • 在检查之前您无需等待fetch() 完成
  • 这是一个异步函数,这意味着它的结果将不可用,除非你在 promise 的 .then 中,或者等待它。
  • fetcher.fetch().then(/* check result in here*/)
  • 或使用 Jest 计时器模拟 jestjs.io/docs/en/timer-mocks

标签: javascript typescript async-await request-promise


【解决方案1】:

感谢TKoL 的 cmets 找到了答案,再看一个我已经阅读了 50 次的文档,即:Jest async testing。我应该更仔细地 RTFM...

测试代码也必须是异步的。

import { HtmlFetcher } from './htmlFetcher.service';

describe('Fetch HTML', () => {

  it('should fetch the HTMl at the given link', async () => { // Added async keyword
    const uri = 'http://help.websiteos.com/websiteos/example_of_a_simple_html_page.htm';
    const fetcher = new HtmlFetcher(uri);
    await fetcher.fetch(); // Added await keyword

    expect(fetcher.html).toBeDefined();
  });

});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-16
    相关资源
    最近更新 更多