reactjs - 模拟交叉获取

标签 reactjs mocking jestjs next.js

我在 Next/React 项目上通过节点使用 Jest 运行测试。
我也在使用交叉提取。
当我尝试为我的组件模拟交叉提取时

import crossFetch from 'cross-fetch'
jest.mock('cross-fetch')
        crossFetch.mockResolvedValue({
          status: 200,
          json: () => {{ 
            user : testUser 
          }},
        })
        render(<UserProfile />)
getServerSideProps 中的 API 请求
总是返回 500
export async function getServerSideProps({ query: { userId } }) {
  let user = null
  let code = 200
  try {
    let response = await fetch(`https://example.com/users/${userId}`, { method: 'GET' }) 
    let statusCode = response.status
    let data = await response.json()
    if (statusCode !== 200) {
      code = statusCode
    } else {
      user = data.user
    }
  } catch (e) {
    console.log(e.message)
  }
  return {
    props: {
      user,
      code,
    },
  }
}
我觉得这与从 Node 启动的测试有关,而 testing-library 库正在模拟浏览器,发出请求的实际库并未针对正确的执行环境(在我的情况下为浏览器)进行模拟。但我不完全确定。
提前致谢

最佳答案

也许它不起作用,因为默认导出是一个函数。试试这个:

//test.js
import crossFetch from 'cross-fetch';

jest.mock('cross-fetch', () => {
  //Mock the default export
  return {
    __esModule: true,
    default: jest.fn()
  };
});

test('should do a mock fetch', () => {
  crossFetch.mockResolvedValue({
    status: 200,
    json: () => {{ 
      user: testUser 
    }},
  });
  expect(crossFetch().status).toEqual(200);
});

关于reactjs - 模拟交叉获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63256380/

相关文章:

javascript - JEST 抛出 .finally 不是一个函数

javascript - 使用单独的代码和 View 响应 native 明文输入

javascript - 在 React 中使用 Buttons 触发 react-table 上的过滤功能

c# - 如何在 C# 中创建用于测试目的的模拟任务对象?

mocking - Rspec、 stub 方法并返回预定义值

unit-testing - 何时使用严格模拟?

javascript - 模拟与导入然后模拟

javascript - 错误 : Expected mock function to have been called

javascript - <table> 标记上存在未知属性 `selectable`。在 Material UI 中

node.js - 如何将 create-react-app 作为大型网站的子目录提供服务?