使用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

有什么帮助吗?

我开始工作了:对于任何需要将提取模拟为理智函数的人:

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

最新更新