I'm trying to create some basic tests using karma server and nock. It seems like nock is not intercepting my requests at all, does anyone have idea? I can't figure out what is missing. I still getting real data.
nock('https://api.github.com/users/' + username).log(console.log)
.get('/')
.query(true)
.reply(400, {
statusMessage: 'Bad Request',
foo: 'foo'
})
http.get('https://api.github.com/users/' + username, function(res) {
console.log('res', res)
})
I also added this middleware
const middlewares = [thunk];
const mockStore = configureStore(middlewares);
====== UPDATE Jun 6 ======
Whole flow using react-redux Here is my test:
import configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import axios from 'axios';
import expect from 'expect';
import * as actions from 'actions/test-actions'
import * as types from 'types';
import nock from 'nock'
import { username } from 'constansts'
const middlewares = [thunk];
const mockStore = configureStore(middlewares);
describe('Asynchronous actions', () => {
it('Basic example', done => {
nock('https://api.github.com')
.get('/users/' + username)
.reply(400, {
statusMessage: 'Bad Request',
foo: 'foo'
})
var expectedActions = []
let store = mockStore([], expectedActions, done)
store.dispatch(actions.testRequest())
.then(() => {
console.log('store.getActions() => ', store.getActions())
})
.then(done).catch((err) => {
console.log('ERROR==>', err)
done()
})
})
})
And here is the action
export function testRequest () {
return axios.get('https://api.github.com/users/' + username)
.then(function (res) {
console.log('response =>', res.status)
})
.catch(function (err) {
console.log('error =>', err)
})
}
res.status is 200, even if I use nock for changing to 400
This is an old question but I believe the answer is that you need to set the axios
http adapter:
import axios from 'axios';
axios.defaults.adapter = require('axios/lib/adapters/http');
When running tests with jest
you generally run them in a "browser like" environment. To get axios to use the node http library instead you need to specifically tell it to use the http
adapter.
https://github.com/axios/axios/tree/master/lib/adapters
You should specify the path in the get
method:
nock('https://api.github.com').log(console.log)
.get('/users/' + username)
.query(true)
.reply(400, {
statusMessage: 'Bad Request',
foo: 'foo'
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With