这是包含fetch调用的文件,它只发送一些本地存储的json文件.

// eslint-disable-next-line import/prefer-default-export
export const get = () => {
  // eslint-disable-next-line no-undef
  return fetch('data/posts.json').then((res) => res.json());
};

在我的测试中,我模拟了fetch方法和Promise.resolve模拟array.

import { get } from './posts';

const mockData = [
  {
    "id": "ig-1",
    "accountId": "IG",
    "accountIcon": "/images/ig-icon.svg",
    "accountName": "IG account",
    "accountImageInitial": "J",
    "imageUrl": "/images/social_logo.png",
    "caption": "test",
    "timestamp": 1635510651638
  },
  {
    "id": "fb-1",
    "accountId": "FB",
    "accountIcon": "/images/fb-icon.svg",
    "accountName": "FB account",
    "accountImageInitial": "J",
    "imageUrl": "/images/social_logo.png",
    "caption": "test",
    "timestamp": 1635510051638
  }
];

global.fetch = jest.fn(() => 
  Promise.resolve({
    json: () => Promise.resolve(mockData)
  })
);

describe('The posts API controller', () => {
  test('get() returns expected default payload', async () => {
    const result = await get();
    expect(fetch).toHaveBeenCalledTimes(1);
    expect(result).toBeTruthy();
  });
});

错误

Type错误: Cannot read properties of undefined (reading 'then')

Type错误: Cannot read properties of undefined (reading 'then')

      2 | export const get = () => {
      3 |   // eslint-disable-next-line no-undef
    > 4 |   return fetch('data/posts.json').then((res) => res.json());
        |          ^
      5 | };

enter image description here

不确定为什么会出现此错误,因为我似乎正确地模拟了fetch?

推荐答案

我建议只返回res.json(),实际上你已经在隐式地做了.

所以,试试下面的内容.

export const get = () => {
  fetch('https://jsonplaceholder.typicode.com/posts')
    .then((res) => res.json()) // this is an implicit return
    .catch((err) => console.log(err));
};

或使用异步/等待

const get = async () => {
  try {
    const res = await fetch('https://jsonplaceholder.typicode.com/posts');
    return res.json();
  } catch (error) {
    console.log(error);
  }
};

Javascript相关问答推荐

我无法使用tailwind-css和reactJS修改图像的位置

导入图像与内联包含它们NextJS

Vue-Router渲染组件但不更改网址

如何在不使用类型化数组的情况下将32位浮点数按位转换为整值?

React Hooks中useState的同步问题

ReactJS中的material UI自动完成类别

在JavaScript中声明自定义内置元素不起作用

v—自动完成不显示 Select 列表中的所有项目

如何在bslib nav_insert之后更改导航标签的CSS类和样式?

保持物品顺序的可变大小物品分配到平衡组的算法

变量的值在Reaction组件中的Try-Catch语句之外丢失

rxjs插入延迟数据

邮箱密码重置链接不适用于已部署的React应用程序

按下单键和多值

将嵌套数组的元素乘以其深度,输出一个和

无法设置RazorPay订阅API项目价格

Reaction即使在重新呈现后也会在方法内部保留局部值

在JavaScript中,有没有一种方法可以迭代字符串的词法标记?

使用可配置项目创建网格

在Puppeteer中使用promise进行日志(log)记录时出现TargetCloseError