I want to mock API functions inside my saga tests but I couldn't because typescript complains that it's a read-only property. Here's my code.
// src/api/todos.ts
import axios from './utils/axios'
import { handleError } from './error'
export const fetchTodosApi = async () => {
return axios.get(`/todos/`).catch(handleError)
}
I have index.ts
that exports all API functions like so:
export { fetchTodosApi } from './todos'
Then my test saga:
// src/tests/fetchTodos
import { runSaga } from 'redux-saga'
import { fetchTodos } from 'sagas'
import * as api from 'api'
describe('testing fetchTodosApi ', () => {
it('is able to fetch todos', async () => {
const dispatchedActions: Array<any> = []
api.fetchTodosApi = jest.fn(() => Promise.resolve({}))
const fakeStore: any = {
dispatch: (action: any) => dispatchedActions.push(action),
getState: () => state,
}
await runSaga(fakeStore, fetchTodos, action).toPromise()
expect(dispatchedActions[0].todos).toEqual({})
})
})
The problem is I can't assign api.fetchTodosApi
with a mock function cos it's a read-only property as per Typescript. If I change how api function are exported in index.ts
in the api dir to something like:
import { fetchTodosApi } from './todos'
const api = { fetchTodosApi }
export default api
I can assign a mock function to api.fetchTodosApi
but it retains its original definition, not from the mock function. How do I get around this? It works with vanilla Javascript as shown here: https://www.youtube.com/watch?v=a9f97afxa9A
Aucun commentaire:
Enregistrer un commentaire