node.js - 单元测试 Jest Node Fetch
问题描述
我正在尝试测试类方法的返回值。
此类方法从 API 中获取。
在测试时,我决定模拟 fetch 请求,这样我就不会访问网络。
我该怎么做?最好没有外部库。
A类
class ClassA {
constructor() {
}
fetchSpotDate(pair) {
const url = 'url';
const query = 'query';
fetch(url + query)
.then(response => response.json())
.then(json => new Date(json.settlement_date + "Z"))
.catch(e => {
log.error(e)
});
}
}
测试
it('should return correct date object format', async () => {
const mockSuccessResponse = {
foo: 'bar',
settlement_date: '2020-06-29T00:00:00'
};
const mockJsonPromise = Promise.resolve(mockSuccessResponse);
const mockFetchPromise = Promise.resolve({json: () => mockJsonPromise})
const expectedReturn = new Date("2020-06-29T00:00:00Z")
global.fetch = jest.fn(() => mockFetchPromise);
const classA = new ClassA();
const result = await classA.fetchSpotDate('EURUSD')
expect(???result Promise value???).toEqual(expectedReturn)
});
解决方案
推荐阅读
- javascript - Express.js: How do I make a GET request with empty parameters?
- php - 如何插入在无限加载的 WordPress 循环中每 5 个帖子之后?
- spring - Spring SAML:SAMLException:不支持的请求
- iframe - How to utilize external form and retrieve POST data from external form using SuiteScript?
- pug - 从 pug 模板调用 facebook 像素函数
- c# - WPF MVVM 在按钮单击时在视图之间导航
- r - Using sapply on column with missing values
- python - 通过子进程库的 Python discord bot 错误
- php - 从下拉php(数组)打印正确的值
- laravel - Laravel 身份验证会话超时