Created
February 3, 2021 05:27
-
-
Save alphaolomi/3b6336d0da0d0dfac128070d18d38d35 to your computer and use it in GitHub Desktop.
Axios Mocking with Typescript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// users.test.ts | |
import axios from 'axios'; | |
import Users from '../src/users'; | |
jest.mock('axios'); | |
const mockedAxios = axios as jest.Mocked<typeof axios>; | |
let us: Users; | |
beforeAll(() => { | |
us = new Users(); | |
}); | |
test('should fetch users', () => { | |
const users = [{ name: 'Bob' }]; | |
const resp = { data: users }; | |
mockedAxios.get.mockResolvedValue(resp); | |
// or you could use the following depending on your use case: | |
// axios.get.mockImplementation(() => Promise.resolve(resp)) | |
return us.all().then(data => expect(data).toEqual(users)); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// users.ts | |
import axios from 'axios'; | |
export class Users { | |
constructor() {} | |
all() { | |
return axios.get('/users.json').then(resp => resp.data); | |
} | |
} | |
export default Users; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment