簡體   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

這是包含 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模擬數組。

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

錯誤

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

在此處輸入圖像描述

不確定我為什么會收到此錯誤,因為我似乎正確地模擬了 fetch ?

我建議只返回res.json() ,您實際上已經在隱式執行。 此外,在 .then() 之后.then()最好使用.catch()以防在獲取過程中遇到錯誤。

所以,嘗試跟隨。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM