Reputation: 13784
Is there a way to test a service using jest? I was trying to do that but the test doesn't seem to run.
import { postAuthUser } from '../authService';
it('login user', () => {
return postAuthUser({ username: 'user', password: 'password' }).then( data => {
expect(data).toEqual({});
});
});
I have this, I am trying to consume a service but for some reason, it doesn't work.
Upvotes: 0
Views: 1982
Reputation: 102497
I assume your postAuthUser
method of authService
use axios
like this:
authService.ts
import axios from 'axios';
export async function postAuthUser(auth) {
return axios.post('https://github.com/mrdulin', auth);
}
Unit test:
import { postAuthUser } from './authService';
import axios from 'axios';
jest.mock('axios', () => {
return {
post: jest.fn()
};
});
describe('authService', () => {
describe('#postAuthUser', () => {
it('login user', () => {
(axios.post as jest.MockedFunction<typeof axios.post>).mockResolvedValueOnce({});
return postAuthUser({ username: 'user', password: 'password' }).then(data => {
expect(data).toEqual({});
expect(axios.post).toBeCalledWith('https://github.com/mrdulin', { username: 'user', password: 'password' });
});
});
});
});
Unit test result with 100% coverage:
PASS src/stackoverflow/53934331/authService.spec.ts
authService
#postAuthUser
✓ login user (5ms)
----------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
authService.ts | 100 | 100 | 100 | 100 | |
----------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 3.483s, estimated 4s
Here is the completed demo: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/53934331
Upvotes: 3