使用nock和tape

时间:2016-08-10 09:28:58

标签: javascript unit-testing testing redux fetch

我试图在React-Redux中编写一个简单的登录信息,当我尝试测试登录操作时,我遇到了问题。

我一直在关注官方Redux文档中的指南,如何使用fetch的指南,以及如何测试异步/ ajax操作的指南,但是当我编写自己的ajax调用时,我似乎无法通过我写的测试。

我还是React / Redux / Nock / Tape / Fetch的新手,所以这可能是一个超级新秀问题,我为此道歉。

我的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 }));
  };
}

我的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' }))
});

来自testem的结果:

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

0 个答案:

没有答案