I encountered an issue with mocking axios when it uses the config convention `axios(passAConfigObj)
`. I'm able to mock successfully when using `axios.get
` or `axios.post
`, but not with the former. I don't want to rely on a library for this task as I believe it can be accomplished without one.
I attempted to mock the request method that will be used with `axios.post
`. When mocking axios and providing a return value, I received an error requesting an `AxiosPromise<any>
`.
const mockedAxios = mocked(axios)
mockedAxios.mockImplementationOnce(() => Promise.resolve(2))
error: TS2322: Type 'Promise<number>' is not assignable to type AxiosPromise<any>
// auth.spec.ts
import { getAuthToken } from '../auth'
import axios from 'axios'
import { mocked } from 'ts-jest/utils'
jest.mock('axios')
describe('getAuthToken', () => {
const mockedAxiosPost = mocked(axios)
it('should return ', () => {
mockedAxiosPost.mockImplementationOnce(() =>
Promise.resolve({ data: 'response.data' })
)
const authToken = getAuthToken()
expect(authToken).toEqual()
expect(mockedAxiosPost).toHaveBeenCalledTimes(1)
expect(mockedAxiosPost).toHaveBeenCalledWith()
})
})
// auth.ts
import axios from 'axios'
export const getAuthToken = () => {
const options = {
url: `url`,
method: 'POST',
headers: {
Authorization: ''
'Content-Type': '',
},
data: {},
}
return axios(options)
.then(response => {
return response
})
.catch(error => {
console.log(error.response)
})
}
The goal is for axios, when passed a config, to internally call axios.post
, thereby passing my test. While other implementations of axios.post and axios.get work with this testing style, this particular scenario poses a challenge. Although switching to axios.post
would solve the issue, I am intrigued by finding a solution in this context. Thank you for your assistance :)