[英]Jest mock test using Sanity npm package
我的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 模擬為理智的 function 的人:
jest.mock('@sanity/client', () => {
return function sanity() {
return {
fetch: () => ({
methodOne: [{}],
methodTwo: [{}],
}),
};
};
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.