gpt4 book ai didi

javascript - 使用 Sanity npm 包开 Jest 模拟测试

转载 作者:行者123 更新时间:2023-12-05 04:49:25 27 4
gpt4 key购买 nike

我的 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 不是函数

有什么帮助吗?

最佳答案

我得到了它的工作:对于任何你需要模拟获取作为理智功能的人:

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

关于javascript - 使用 Sanity npm 包开 Jest 模拟测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67593147/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com