javascript - 使用 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
有什么帮助吗?
解决方案
我让它工作:对于任何你需要模拟 fetch 作为理智功能的人:
jest.mock('@sanity/client', () => {
return function sanity() {
return {
fetch: () => ({
methodOne: [{}],
methodTwo: [{}],
}),
};
};
});
推荐阅读
- excel - VBA将当前工作表复制到新工作簿并保存
- dart - 使用 dart 在基于以太坊的 Cleo 测试网中发布智能合约
- powershell - 如何获取当前登录的人的用户名并进一步使用?
- asp.net - BulletedList 手动添加多个
- php - AWS kinesis getRecords 返回空 Records[]
- android - 明智地动态创建按钮行列
- ios - 是否可以在 iOS 中使用 URL 将媒体文件共享到 Instagram?
- python - 关键字开始循环和结束循环
- c# - Azure 存储 blob 无法加载文件或程序集 'System.Diagnostics.DiagnosticSource,Version=4.0.4.0,Culture=neutral,PublicKeyToken=cc7b13ffcd
- typescript - axios 中的模拟吸气剂