获取处理承诺

时间:2017-09-25 10:31:03

标签: reactjs promise fetch

我在我的应用中使用此设置:

  • ReactJS
  • KarmaJS
  • Instanbul

此时我一直收到此错误: Object is not a constructor (evaluating '(0, _whatwgFetch2['default'])')

在检查网络时,它一直告诉我要导入我实际上已经做过的whatwg-fetch,所以我有点迷路了。

执行调用的方法:

import fetch from 'whatwg-fetch';

export function authenticateUser(username, password) {

  return function (dispatch, getState) {
    dispatch({type: 'LOGIN'});

    return fetch(getState().config.components.Authentication.login_endpoint, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      credentials: 'same-origin',
      body: JSON.stringify({
        username: username,
        password: password,
      })
    }).then(resp => {
      if (resp.status === 302) {
        window.location = resp.url;
      } else if (resp.status >= 300 && resp.status < 500) {
        return Promise.resolve(resp);
      } else {
        return Promise.reject(resp.statusText);
      }
    }).then(resp => resp.json())
      .then(resp => {
        const error = data.errors[0];
        dispatch({ type: 'LOGIN_FAILED', payload: error.detail });
    }).catch(error => {
      console.error(error); // I know, still needs to be catched 
    });
  };
}

我的测试用例:

import { expect } from 'chai';
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import sinon from 'sinon';
import { authenticateUser } from '../../src/actions/index';

const initialConfig = {
  authentication: {
    loginform_loading: false,
    loginform_errorMessage: null,
    forgotpassword_loading: false,
    forgotpassword_errorMessage: null,
    forgotpassword_passwordSent: false
  },
  config: {
    components: {
      Authentication: {
        'login_endpoint': '/api/auth/login',
        'forgotpassword_enabled': true,
        'forgotpassword_path': '/auth/forgot-password',
        'forgotpassword_endpoint': '/auth/forgot-password'
      }
    }
  }
};

const middlewares = [ thunk ];
const mockStore = configureMockStore(middlewares);
let store;

describe('Action/Index/authenticateUser', () => {

  const testUsername = 'User';
  const testPassword = 'Test123';
  let sandbox;

  beforeEach(function () {
    sandbox = sinon.sandbox.create();
    store = mockStore(initialConfig);
  });

  afterEach(function () {
    sandbox.restore();
  });

  it('LOGIN is dispatched', () => {
    var response = mockResponse(400, 'Found', '{"errors": [{ "message": "first" }] }');
    sandbox.stub(window, 'fetch')
      .resolves(response);

    return store.dispatch(authenticateUser(testUsername, testPassword))
      .then(() => {
        var expectedActions = store.getActions();
        expect(expectedActions).to.not.be.empty;

        var action = expectedActions[0];
        expect(action.type).to.equal('LOGIN');
      });
  });
});

希望有人可以帮助我解决问题。也许还有关于如何改进Promise本身的错误处理

谢谢, 皮姆

1 个答案:

答案 0 :(得分:0)

Panther在这个问题上给出了正确答案。

import 'whatwg-fetch'做了这个伎俩