首页 > 解决方案 > 使用 Sanity npm 包的 Jest 模拟测试

问题描述

我的sanity.ts文件中有一些代码:

import sanityClient from '@sanity/client';

// eslint-disable-next-line @typescript-eslint/no-var-requires
const blocksToHtml = require('@sanity/block-content-to-html');

const client = sanityClient({
  projectId: '',
  dataset: '',
  apiVersion: '2021-05-11',
  token: String(process.env.SANITY_API_KEY),
  useCdn: false,
});

export async function getData(): Promise<void> {
  const query = '';
  const sanityResponse = await client.fetch(query);

  return;
}

我在测试它时试图模拟它,但我在设置模拟时遇到问题。我不断得到TypeError: client_1.default is not a function。这是我在 Jest 测试文件中的内容:

jest.mock('@sanity/client', () => {
  const mClient = {
    fetch: jest.fn(),
  };
  return { client: jest.fn(() => mClient) };
});

我究竟做错了什么?

更新:

__mocks__使用以下代码创建了一个文件夹并得到了不同的错误:

class sanityClient {}
const client = jest.fn(() => new sanityClient());

const fetchMock = jest.fn();

client.prototype = {
  fetch: fetchMock,
};

module.exports = sanityClient;
module.exports.client = client;
module.exports.fetch = fetchMock;

TypeError: client.fetch is not a function

有什么帮助吗?

标签: javascriptnode.jsunit-testingnpmjestjs

解决方案


我让它工作:对于任何你需要模拟 fetch 作为理智功能的人:

jest.mock('@sanity/client', () => {
  return function sanity() {
    return {
      fetch: () => ({
        methodOne: [{}],
        methodTwo: [{}],
      }),
    };
  };
});

推荐阅读