Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add testing example to README #309

Merged
merged 3 commits into from
Apr 20, 2023
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -366,6 +366,44 @@ CANCEL_ERROR 'CANCEL_ERROR' --- Request has been cancelled. On

Which problem is chosen will be picked by walking down the list.

# Mocking with axios-mock-adapter (or other libraries)

A common testing pattern is to use `axios-mock-adapter` to mock axios and respond with stubbed data. These libraries mock a specific instance of axios, and don't globally intercept all instances of axios. When using a mocking library like this, it's important to make sure to pass the same axios instance into the mock adapter.

This example will *not* work. `axios-mock-adapter` will not intercept the request and mock the response:
```javascript
import apisauce from 'apisauce'
import MockAdapter from 'axios-mock-adapter'

test('mock adapter', async () => {
const api = apisauce.create("https://api.github.com")
const mock = new MockAdapter(axios)
mock.onGet("/repos/skellock/apisauce/commits").reply(200, {
commits: [{ id: 1, sha: "aef849923444" }],
});

const response = await api..get('/repos/skellock/apisauce/commits')
expect(response.data[0].sha).toEqual"aef849923444")
})
```

Instead, create the MockAdapter using the axiosInstance exposed by apisauce. This example will work:
```javascript
import apisauce from 'apisauce'
import MockAdapter from 'axios-mock-adapter'

test('mock adapter', async () => {
const api = apisauce.create("https://api.github.com")
const mock = new MockAdapter(api.axiosInstance)
mock.onGet("/repos/skellock/apisauce/commits").reply(200, {
commits: [{ id: 1, sha: "aef849923444" }],
});

const response = await api..get('/repos/skellock/apisauce/commits')
expect(response.data[0].sha).toEqual"aef849923444")
})
```

# Contributing

Bugs? Comments? Features? PRs and Issues happily welcomed! Make sure to check out our [contributing guide](./github/CONTRIBUTING.md) to get started!