首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >nock和Redux操作测试-模拟存储错误

nock和Redux操作测试-模拟存储错误
EN

Stack Overflow用户
提问于 2017-03-08 05:07:36
回答 1查看 780关注 0票数 0

我刚开始进行redux测试,并且一直在尝试支持一个应用程序的填充测试,如果这是使用nock和redux模拟商店进行测试的完全错误的话,我非常抱歉。

代码语言:javascript
复制
//Action in authAction.js
export function fetchMessage() {
  return function(dispatch) {
    axios.get(ROOT_URL, {
      headers: { authorization: localStorage.getItem('token') }
    })
      .then(response => {
        console.log("hi")
        dispatch({
          type: FETCH_MESSAGE,
          payload: response.data.message
        });
      })
      .catch(response => {
        console.log(response)
        //callingRefresh(response,"/feature",dispatch);
      });
  }
}

这就是方法,它似乎正在被调用,但通常会转到标题不匹配的nock失败原因的捕捉原因。

代码语言:javascript
复制
//authActions_test.js
import nock from 'nock'
import React from 'react'
import {expect} from 'chai'
import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'

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

import * as actions from '../../src/actions/authActions';
const ROOT_URL = 'http://localhost:3090';

describe('actions', () => {

    beforeEach(() => {
        nock.disableNetConnect();
        localStorage.setItem("token", '12345');
    });

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


  describe('feature', () => {

    it('has the correct type', () => {
      var scope = nock(ROOT_URL).get('/',{reqheaders: {'authorization': '12345'}}).reply(200,{ message: 'Super secret code is ABC123' });
      const store = mockStore({ message: '' });

      store.dispatch(actions.fetchMessage()).then(() => {
      const actions = store.getStore()
      expect(actions.message).toEqual('Super secret code is ABC123');
    })


    });
  });
});

即使头被移除,nock也会拦截调用。我每次都会收到这个错误

代码语言:javascript
复制
TypeError: Cannot read property 'then' of undefined
  at Context.<anonymous> (test/actions/authActions_test.js:43:24)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-03-08 05:26:08

您不会从axios返回链接then调用的承诺。

将雷声改为:

代码语言:javascript
复制
//Action in authAction.js
export function fetchMessage() {
  return function(dispatch) {
    return axios.get(ROOT_URL, {
      headers: { authorization: localStorage.getItem('token') }
    })
      .then(response => {
        console.log("hi")
        dispatch({
          type: FETCH_MESSAGE,
          payload: response.data.message
        });
      })
      .catch(response => {
        console.log(response)
        //callingRefresh(response,"/feature",dispatch);
      });
  }
}

您还可能需要更改测试,以便在承诺解决之前不会通过测试。如何进行此更改取决于所使用的测试库。如果你在使用摩卡,看看this answer

附带注意:我不确定您是否有其他单元测试单独测试动作创建者到还原器,但这是一个非常完整的方法来测试这些。Redux最大的优点之一是,机器上的每一个分离的齿轮都能很容易地彼此隔离测试。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42663416

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档