javascript - 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. eslint-d

This is the file containing the fetch call, which just sends some locally stored json file.

// 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.

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: 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?

This is the file containing the fetch call, which just sends some locally stored json file.

// 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.

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: 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?

Share Improve this question asked Jul 9, 2022 at 1:54 Leon GabanLeon Gaban 39.1k122 gold badges349 silver badges550 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 1

I would suggest just to return the res.json(), which you are actually already doing implicitly. Also, after .then() it's good practice to have .catch() in case you encounter an error during fetching.

So, try following.

export const get = () => {
  fetch('https://jsonplaceholder.typicode./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./posts');
    return res.json();
  } catch (error) {
    console.log(error);
  }
};

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745281112a4620284.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信