Skip to content

Instantly share code, notes, and snippets.

@alphaolomi
Created February 3, 2021 05:27
Show Gist options
  • Save alphaolomi/3b6336d0da0d0dfac128070d18d38d35 to your computer and use it in GitHub Desktop.
Save alphaolomi/3b6336d0da0d0dfac128070d18d38d35 to your computer and use it in GitHub Desktop.
Axios Mocking with Typescript
// 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));
});
// 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