Skip to content

Commit

Permalink
Link markdown.
Browse files Browse the repository at this point in the history
  • Loading branch information
danawoodman committed Feb 27, 2018
1 parent c0c01ab commit a8f9b79
Showing 1 changed file with 21 additions and 14 deletions.
35 changes: 21 additions & 14 deletions docs/MockFunctions.md
Original file line number Diff line number Diff line change
Expand Up @@ -129,41 +129,48 @@ function that's not directly being tested.

## Mocking Modules

Suppose we have a class that fetches users from our API. The class uses [axios](https://github.com/axios/axios) to call the API then returns the `data` attribute which contains all the users:
Suppose we have a class that fetches users from our API. The class uses
[axios](https://github.com/axios/axios) to call the API then returns the `data`
attribute which contains all the users:

```js
// users.js
import axios from 'axios'
import axios from 'axios';

class Users {
static all() {
return axios.get('/users.json').then(resp => resp.data)
return axios.get('/users.json').then(resp => resp.data);
}
}

export default Users
export default Users;
```

Now, in order to test this method without actually hitting the API (and thus creating slow and fragile tests), we can use the `jest.mock(...)` function to automatically mock the axios module.
Now, in order to test this method without actually hitting the API (and thus
creating slow and fragile tests), we can use the `jest.mock(...)` function to
automatically mock the axios module.

Once we mock the module we can spy on the `.get` method and provide a `mockImplementation` that returns the data we want our test to assert against. In effect, we are saying that we want axios.get('/users.json') to return a fake response.
Once we mock the module we can spy on the `.get` method and provide a
`mockImplementation` that returns the data we want our test to assert against.
In effect, we are saying that we want axios.get('/users.json') to return a fake
response.

```js
// users.test.js
import axios from 'axios'
import Users from './users'
import axios from 'axios';
import Users from './users';

jest.mock('axios')
jest.mock('axios');

test('should fetch users', () => {
const resp = Promise.resolve({ data: [{ name: 'Bob' }] })
axios.get.mockReturnValue(resp)
const resp = Promise.resolve({data: [{name: 'Bob'}]});
axios.get.mockReturnValue(resp);

// or you could use the follwing depending on your use case:
// or you could use the follwing depending on your use case:
// axios.get.mockImpementation(() => resp)

return Users.all().then(users => expect(users).toEqual(resp.data))
})
return Users.all().then(users => expect(users).toEqual(resp.data));
});
```

## Mock Implementations
Expand Down

0 comments on commit a8f9b79

Please sign in to comment.