我有一些代码在我的 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 不是一个函数
需要帮助吗?
sanity.ts
中添加console.log(sanityClient)
进行调试。 - Vitalii