redux - 如何使用nock来测试异步操作

时间:2016-09-19 04:16:25

标签: reactjs redux nock

我按照redux.org的基本例子来测试异步操作

action.js

我的代码是这样的:

import axios from 'axios'

export function getGoodDataStart(){
    return{
        type: "GOOD_DATA_START"
    }
}
export function getGoodDataSuccess(payload){
    console.log('success', payload)
    return {
        type: "GOOD_DATA_SUCCESS",
        payload: payload
    }
}
export function getGoodDataFail(){
    return{
        type: "GOOD_DATA_FAIL"
    }
}
export function getGoodData(){
    return (dispatch) => {
        dispatch( getGoodDataStart() )
        return  axios.get('http://www.google.com/list')
            .then( response => {
                console.log('fake res',response)
                dispatch(getGoodDataSuccess (response) )
            })
            .catch( err => {
                console.log('fake err',err)
            })
    }   
}

test.js

import nock from 'nock'
import React from 'react'
import {expect} from 'chai'
import {getGoodData} from 'registerAction'
import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'

const middlewares = [ thunk ]
const mockStore = configureMockStore(middlewares)

describe('Register component', () => {

    it('async action', function () {

        nock('http://www.google.com')
        .get('/list')
        .reply(200,'ok!' )

        const store = mockStore({ 
            myData: '' ,
        })
        const expected = [
            {type: "GOOD_DATA_START"},
            {type: "GOOD_DATA_SUCCESS", payload: 'ok!'}
        ]

        return store.dispatch(getGoodData())
            .then( () => { 
                expect(store.getActions()).to.equal(expected)
            })
    })
})

我遇到的问题是,nock没有阻止请求,它让函数getGoodData向google.com发出真实请求。我做错了什么?

错误的屏幕截图:

enter image description here

以下是演示:https://github.com/craigcosmo/react-redux-test

安装:npm i

测试:npm run test

打开网址:http://localhost:5051/webpack-dev-server/

3 个答案:

答案 0 :(得分:3)

通常在测试此类操作时,您需要从等式中删除任何不属于您操作的内容。在这种情况下,通过简单地使用nock,你不会从等式中移除axios,实际上增加了不必要的复杂性。通过使用间谍模拟axios,您可以避免进行网络呼叫,也可以避免调用axios。这允许您简单地声明使用正确的参数调用axios。间谍可以返回一个允许测试所有承诺处理和后续动作调用的承诺。为了证明这一点,我需要添加一个提供间谍的库,所以我选择为断言和间谍添加'expect',但如果你想坚持使用chai,你可以轻松地对sinon做同样的事情。

这是一个你根本不需要nock的例子,你只是用间谍模拟axios:

import React from 'react'
import * as registerAction from 'registerAction'
import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'
import expect from 'expect'

const middlewares = [ thunk ]
const mockStore = configureMockStore(middlewares)

// set up to mock axios methods
import axios from 'axios'
const _get = axios.get

const fakePayload = { foo: 'bar' };
describe('Register component', () => {
    beforeEach(() => {
        // replace the .get method temporarily with a spy
        axios.get = expect.createSpy().andReturn(Promise.resolve(fakePayload));
    })

    afterEach(() => {
        // restore the get method with our saved const
        axios.get = _get;
    })

    it('async action', function () {
        const store = mockStore({
            myData: '' ,
        })
        const expected = [
            {type: "GOOD_DATA_START"},
            {type: "GOOD_DATA_SUCCESS", payload: fakePayload}
        ]

        return store.dispatch(registerAction.getGoodData())
            .then( () => {
                expect(store.getActions()).toEqual(expected)
                expect(axios.get).toHaveBeenCalled()
                expect(axios.get).toHaveBeenCalledWith('http://www.google.com/list')
            })
    })
})

答案 1 :(得分:1)

阅读https://github.com/node-nock/nock/issues/150

您的测试在控制台上做得很好 -

在package.json

上添加这两个脚本
    "itest": "mocha --compilers js:babel-register -R spec  \"test/*.test.js\"",
    "itest:watch": "npm run itest -- --watch"

答案 2 :(得分:0)

你可能需要这样的东西

beforeEach(() => {
    nock.disableNetConnect();
});

afterEach(() => {
    nock.cleanAll();
    nock.enableNetConnect();
});

Enable/Disable real HTTP Request