mercredi 10 août 2016

Can't get a successful test with async ajax requests using nock and tape

I'm trying to write a simple login in React-Redux and I'm running into a problem when I try and test my login action.

I've been following guides from official Redux documentation, guides on how to use fetch, and guides on how to test async/ajax actions but when I write my own ajax call I can't seem to pass the test I have written.

I'm still quite new to React/Redux/Nock/Tape/Fetch so this may be a super rookie question and I do apologise for that.

My LoginActions.js:

import { API_URL } from '../../../globals.js';
import fetch from 'isomorphic-fetch';
/*
 * action types
 */

export const LOGIN_SUCCESS = 'LOGIN_SUCCESS';
export const LOGIN_FAILED = 'LOGIN_FAILED';
export const LOGIN_ATTEMPT = 'LOGIN_ATTEMPT';

/*
 * action creators
 */

export function loginAttemptSuccess({ priviledge, userId, username }) {
  return { type: LOGIN_SUCCESS, priviledge, userId, username };
}

export function loginAttemptFailed({ error }) {
  return { type: LOGIN_FAILED, error };
}

export function loginAttempt({ username, password }) {
  // const PostData = { username, password };

  return function (dispatch) {
    return fetch(`${API_URL}/login/login.php`, {
      method: 'GET'
    })
      .then(response => dispatch({ type: LOGIN_SUCCESS }))
      .catch(error => dispatch({ type: LOGIN_FAILED }));
  };
}

My LoginActions.spec.js:

import { API_URL } from '../../../globals.js';
import test from 'tape';
import configureStore from 'redux-mock-store';
import thunkMiddleware from 'redux-thunk';
import sinon from 'sinon';
import nock from 'nock';
import * as LoginActions from './LoginActions.js';


test('Login Attempt on success should return true', (t) => {
  t.plan(1);

    nock(`${API_URL}`)
      .get('/login/login.php')
      .reply(200, { body: { todos: ['do something'] }})

  const initialState = { todos: [] };

  const store = mockStore(initialState);

  const dispatch = sinon.spy(store, 'dispatch');
  const fn = LoginActions.loginAttempt('one', 'two');

  fn(dispatch, store.getState);

  t.true(dispatch.calledWith({ type: 'FETCH_TODOS_SUCCESS' }))
});

Result from testem:

# Login Attempt on success should return true
not ok 4 should be truthy
  ---
    operator: ok
    expected: true
    actual:   false
  ...

Aucun commentaire:

Enregistrer un commentaire