使用 Sanity npm 包的 Jest 模拟测试

时间:2021-05-18 19:56:19

标签: javascript node.js unit-testing npm jestjs

我的 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

有什么帮助吗?

1 个答案:

答案 0 :(得分:0)

我让它工作了:对于任何你需要将 fetch 模拟为理智函数的人:

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