mercredi 17 août 2016

Redux: Nock not triggering dispatch on success

I have this action in my redux application. I am basically writing up a unit test for an API call. I am using nock for this. There's a weird issue I am facing. Even though nock successfully matches the host but still it dispatches the error dispatch function.

Login.actions.js

import * as action from './login.actionCreators';
import {browserHistory} from 'react-router';
import axios from 'axios';
import _ from 'lodash';
import {api} from '../config';

export function loginUser(credentials) {
  return dispatch => {
    dispatch(action.loginRequest());
    return axios({
      method: 'post',
      url: `${api}/login`,
      data: {
        email: _.trim(_.get(credentials, 'email')),
        password: _.get(credentials, 'password')
      }
    })
      .then(response => {
        const { data } = response;

        if (_.isEqual(_.get(response, 'status'), 200)) {
          dispatch(action.loginSuccess(data));
          localStorage.setItem('user', JSON.stringify(data));
          browserHistory.goBack();
        }
      })
      .catch(err => {
        dispatch(action.loginError(err));
      });
  };
}

Login.test.js

import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'
import * as actions from '../../src/login/login.actions';
import * as types from '../../src/login/login.actionTypes.js';
import nock from 'nock';
import {expect} from 'chai';
import {api} from '../../src/config';


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

describe('Login Actions', () => {
  afterEach(() => {
    nock.cleanAll()
  });

  it('create LOGIN_SUCCESS if user is authenticated', (done) => {
    nock(`${api}`)
      .post('/login', {
        email: 'a@a.net',
        password: 'a'
      })
      .reply(200, {body: { data: {email: 'a@a.net' } }})
      .log((body) => {
        console.log(body); //matching API to POST API true
      });

    const expectedActions = [
      { type: types.LOGIN_REQUEST },
      { type: types.LOGIN_SUCCESS,  body: { user: {email : 'a@a.net' }} },
      { type: types.LOGIN_ERROR,  body: {error: 'Something went wrong'} }
    ];

    const store = mockStore({ auth: {} }, expectedActions);
    const credentials = {
      email: 'abc@abc.net',
      password: 'a'
    };
    return store.dispatch(actions.loginUser(credentials))
      .then(() => {
        const loginActions = store.getActions();
        done();
        console.log(loginActions); 
//[ { type: 'LOGIN_REQUEST' },
 // { type: 'LOGIN_ERROR', error: 'Something went wrong' } ]

        expect(loginActions).to.equal(expectedActions);
      });
  });

});

The weird thing is even though i've made expect(loginActions).to.equal(expectedActions); assertion, the test passes. Although it shouldn't. Thank you in advance. I am pretty sure this would turn out to be a silly mistake from my end

Aucun commentaire:

Enregistrer un commentaire