I can't mock axios when it is uses the config convention axios(passAConfigObj)
. I have no problem mocking when it is axios.get
or axios.post
. Not trying to introduce a library, because I feel like this can be done.
I have tried mocking the request method that is going to be used axios.post
. I tried mocking axios and giving it a return value but wants 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)
})
}
I expect axios that gets passed a config to internally call axios.post
thus working/passing my test.
I have other implementations of axios.post and axios.get that works with this testing style, so that is not the problem. Obviously I can just change my code to use axios.post
, but at this point, I am curious more than anything. Thanks in advance :)