4

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

动作.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)
            })
    }   
}

测试.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 发出真正的请求。我究竟做错了什么?

错误的屏幕截图:

在此处输入图像描述

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

安装:npm i

测试: npm run test

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

4

3 回答 3

3

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

这是一个根本不需要 nock 的示例,您只需使用 spy 模拟 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')
            })
    })
})
于 2016-10-15T18:24:47.240 回答
2

阅读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"
于 2016-09-21T19:44:20.863 回答
1

你可能需要这样的东西

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

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

启用/禁用真正的 HTTP 请求

于 2016-09-23T14:49:38.760 回答