【发布时间】: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.html 是 undefined。 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