诺克没有拦截我的请求 [英] nock is not intercepting my request

查看:103
本文介绍了诺克没有拦截我的请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用业力服务器和nock创建一些基本测试. 似乎nock根本没有拦截我的请求,有人知道吗?我不知道丢失了什么.我仍在获取真实数据.

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)
})

我还添加了此中间件

const middlewares = [thunk];
const mockStore = configureStore(middlewares);

=======更新6月6日======

====== UPDATE Jun 6 ======

使用react-redux进行全流程 这是我的测试:

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()
      })
  })
})

这是动作

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

res.status is 200, even if I use nock for changing to 400

推荐答案

这是一个老问题,但我相信答案是您需要设置axios http适配器:

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');

使用jest运行测试时,通常在类似于浏览器"的环境中运行它们.为了使axios使用节点http库,您需要专门告诉它使用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

这篇关于诺克没有拦截我的请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆