Reputation: 352
I have some code in my sanity.ts
file:
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;
}
I'm trying to mock this when I'm testing it, but I'm having issues setting up the mock. I keep getting TypeError: client_1.default is not a function
. This is what I have in my Jest test file:
jest.mock('@sanity/client', () => {
const mClient = {
fetch: jest.fn(),
};
return { client: jest.fn(() => mClient) };
});
What am I doing wrong?
UPDATE:
made a __mocks__
folder with the following code and got a different error:
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
Any help?
Upvotes: 3
Views: 1207
Reputation: 352
I got it to work: For anyone you need to mock the fetch as a function of sanity:
jest.mock('@sanity/client', () => {
return function sanity() {
return {
fetch: () => ({
methodOne: [{}],
methodTwo: [{}],
}),
};
};
});
Upvotes: 3