Skip to content

Instantly share code, notes, and snippets.

@amerryma
Created May 19, 2022 15:55
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amerryma/1399a8728f4dfe590e0dd81519c88d50 to your computer and use it in GitHub Desktop.
Save amerryma/1399a8728f4dfe590e0dd81519c88d50 to your computer and use it in GitHub Desktop.
Supabase Mocking (Regular Mocking vs API Nock)
import { createClient } from '@supabase/supabase-js'
const supabaseUrl = process.env.REACT_APP_SUPABASE_URL
const supabaseAnonKey = process.env.REACT_APP_SUPABASE_ANON_KEY
export const supabase = createClient(supabaseUrl, supabaseAnonKey)
import '@testing-library/jest-dom'
import { render } from '@testing-library/react'
import { renderHook } from '@testing-library/react-hooks'
import nock from 'nock'
import TestComponent from './TestComponent'
const mockResultData = [
{
some: 'response'
}
]
nock.disableNetConnect()
nock(/localhost/)
.post('/rest/v1/rpc/myfunction', {
param1: 'test'
})
.once()
.reply(200, mockResultData)
describe('test component', () => {
it('properly nocks the supabase api', async () => {
const { container } = render(<TestComponent />)
const { waitFor } = renderHook(() => {}, {})
await waitFor(() => {
return nock.isDone()
})
expect(container.getElementsByTagName('pre').item(0).innerHTML).toEqual(JSON.stringify(mockResultData, null, 2))
})
})
import '@testing-library/jest-dom'
import { render } from '@testing-library/react'
import { act, renderHook } from '@testing-library/react-hooks'
import TestComponent from './TestComponent'
const mockResultData = [
{
some: 'response'
}
]
jest.mock('../../utils/supabaseClient', () => ({
__esModule: true,
supabase: {
rpc: jest.fn()
}
}))
describe('test component', () => {
const rpcMock = jest.requireMock('../../utils/supabaseClient').supabase.rpc
beforeEach(() => {
rpcMock.mockReturnValue({
data: mockResultData
})
})
it('properly mocks the supabase singleton', async () => {
const { waitFor } = renderHook(() => {}, {})
const { container } = render(<TestComponent />)
await act(() =>
waitFor(() => {
return expect(rpcMock).toHaveBeenCalled()
})
)
expect(container.getElementsByTagName('pre').item(0).innerHTML).toEqual(JSON.stringify(mockResultData, null, 2))
})
})
import { FC, useEffect, useState } from 'react'
import { supabase } from '../../utils/supabaseClient'
const TestComponent: FC = () => {
const [result, setResult] = useState([])
useEffect(() => {
;(async () => {
const result = await supabase.rpc('myfunction', { param1: 'test' })
setResult(result.data)
})()
}, [])
return <pre>{JSON.stringify(result, null, 2)}</pre>
}
export default TestComponent
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment