I use supabase for my express js backend. This is how I have defined my supabase client:
const config = require('../config/env');
const supabase = require('@supabase/supabase-js');
const supabaseClient = supabase.createClient(
config.supabase.url,
config.supabase.key,
{
auth: {
autoRefreshToken: false,
persistSession: false,
detectSessionInUrl: false,
},
}
);
module.exports = supabaseClient;
An example call to the database can be something like this:
const query = supabaseClient
.from('items')
.select('*')
.eq('id', id);
const { data, error } = await executeWithRetry(async () => await query);
I am writing some tests to test this logic and I would like to mock the supabase calls. This is my jest mock for supabase:
jest.mock('@supabase/supabase-js', () => {
return {
createClient: jest.fn().mockImplementation(() => {
return {
from: jest.fn().mockReturnThis(),
select: jest.fn().mockImplementation(() => ({
eq: jest.fn().mockReturnThis(),
in: jest.fn().mockReturnThis(),
is: jest.fn().mockReturnThis(),
order: jest.fn().mockReturnThis(),
gte: jest.fn().mockReturnThis(),
lte: jest.fn().mockReturnThis(),
execute: jest.fn().mockImplementation(() => {
return Promise.resolve({
data: [{ id: 'some-uuid-text' }],
error: null,
});
}),
})),
};
}),
};
});
and this is the test
describe('userPermissions', () => {
it('should fetch user permissions', async () => {
const email = '[email protected]';
const result = await userPermissions({ email });
expect(result).toEqual([{ role_id: 'mockedRoleId' }]);
});
});
The userPermissions
method has a query that attempts to fetch data from supabase which keeps on responding with undefined
data and undefined
error. My expectation is that it should respond with what's in my execute part of the mock
return Promise.resolve({
data: [{ id: 'some-uuid-text' }],
error: null,
});
What could be causing the issue?
The logic that I was using seemed correct but supabase doesn't have the execute function as part of its functions that's why the supabase calls were not responding with any response because I wasn't passing any data or error. Updating the mock with
data
anderror
to this fixes the issue:To make the mocks more reusable, I went with a variant where I could define the expected data for every test, as seen below:
This is how the mock is used in the actual tests: