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 e09ad8e commit fafee8e
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 fafee8e

Please sign in to comment.