简体   繁体   English

TypeError: Cannot read properties of undefined (reading 'then') - while Mocking Fetch call in Jest

[英]TypeError: Cannot read properties of undefined (reading 'then') - while Mocking Fetch call in Jest

This is the file containing the fetch call, which just sends some locally stored json file.这是包含 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());
};

My test where I mock the fetch method and Promise.resolve a mock array.我在测试中模拟fetch方法并Promise.resolve模拟数组。

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();
  });
});

Error错误

TypeError: Cannot read properties of undefined (reading 'then') TypeError:无法读取未定义的属性(读取“然后”)

TypeError: 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 | };

在此处输入图像描述

Unsure as to why I'm getting this error, as it appears that I have mocked fetch correctly?不确定我为什么会收到此错误,因为我似乎正确地模拟了 fetch ?

I would suggest just to return the res.json() , which you are actually already doing implicitly.我建议只返回res.json() ,您实际上已经在隐式执行。 Also, after .then() it's good practice to have .catch() in case you encounter an error during fetching.此外,在 .then() 之后.then()最好使用.catch()以防在获取过程中遇到错误。

So, try following.所以,尝试跟随。

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

or using async/await或使用异步/等待

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Jest Vuejs 测试 - 类型错误:无法读取未定义的属性(读取“参数”) - Jest Vuejs Test - TypeError: Cannot read properties of undefined (reading 'params') TypeError:无法读取未定义(读取“长度”)JEST 测试的属性 - TypeError: Cannot read properties of undefined (reading 'length') JEST test TypeError:无法在构建时读取未定义的属性(读取“调用”),但在初始化适配器时无法读取 web3auth 的开发 - TypeError: Cannot read properties of undefined (reading 'call') on build but not dev for web3auth while initializing adapter 类型错误:无法读取 Next.js 上未定义的属性(读取“调用”) - TypeError: Cannot read properties of undefined (reading 'call') on Next.js 笑话:- TypeError:无法读取未定义的属性(读取“params”)。 开玩笑时出错 - Jest:- TypeError: Cannot read properties of undefined (reading 'params'). Error coming in jest 开玩笑:无法读取未定义的属性(读取“0”) - Jest: Cannot read properties of undefined (reading '0') 类型错误:无法读取未定义的属性(读取“createdTimestamp”) - TypeError: Cannot read properties of undefined (reading 'createdTimestamp') TypeError:无法读取未定义的属性(读取“forEach”) - TypeError: Cannot read properties of undefined (reading 'forEach') TypeError:无法读取未定义的属性(读取“学生”) - TypeError: Cannot read properties of undefined (reading 'students') TypeError:无法读取未定义的属性(读取“addEventListener”) - TypeError: Cannot read properties of undefined (reading 'addEventListener')
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM