【问题标题】:Mocking cross-fetch模拟交叉获取
【发布时间】:2020-11-25 02:39:06
【问题描述】:

我在 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 库正在模拟浏览器有关,发出请求的实际库没有被模拟为正确的执行环境(在我的情况下是浏览器)。但我不完全确定。

提前致谢

【问题讨论】:

  • 不确定这是否是问题,但 fetch 需要绝对网址。

标签: reactjs mocking jestjs next.js


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-26
    • 2012-11-14
    • 1970-01-01
    • 2019-09-17
    • 1970-01-01
    • 2012-02-13
    • 2019-06-15
    • 1970-01-01
    相关资源
    最近更新 更多