我正在尝试使用karma服务器和nock创建一些基本的测试。看起来nock根本没有拦截我的请求,有谁知道吗?我找不出缺了什么。我还是得到了真实的数据。
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)
})我还添加了这个中间件
const middlewares = [thunk];
const mockStore = configureStore(middlewares);======更新6月6日======
使用react-redux的整个流程是我的测试:
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()
})
})
})这就是行动
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为200,即使我使用nock更改为400
发布于 2018-10-31 00:09:38
这是一个老问题,但我相信答案是您需要设置axios http适配器:
import axios from 'axios';
axios.defaults.adapter = require('axios/lib/adapters/http');在使用jest运行测试时,您通常会在“类似浏览器”的环境中运行它们。要让axios使用node http库,您需要明确地告诉它使用http适配器。
发布于 2016-06-06 21:57:26
您应该在get方法中指定路径:
nock('https://api.github.com').log(console.log)
.get('/users/' + username)
.query(true)
.reply(400, {
statusMessage: 'Bad Request',
foo: 'foo'
});发布于 2016-06-07 07:27:39
我找到答案了!
显然,它与axios没有兼容性,我也尝试过'fetch',‘isomorphic fetch’,但没有成功。
“‘whatwg fetch”是答案
非常感谢,希望这篇文章能对其他人有所帮助。
import 'whatwg-fetch'
export function testRequest () {
return fetch('https://api.github.com/users/' + username)
.then(function (res) {
console.log('response =>', res.status)
})
.catch(function (err) {
console.log('error =>', err)
})
}https://stackoverflow.com/questions/37645242
复制相似问题