Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 测试Redux登录操作_Javascript_Unit Testing_Testing_Redux - Fatal编程技术网

Javascript 测试Redux登录操作

Javascript 测试Redux登录操作,javascript,unit-testing,testing,redux,Javascript,Unit Testing,Testing,Redux,我希望我能就如何测试涉及登录API调用的Redux操作寻求一些帮助。我已经看过一些测试异步操作的示例,但是我还没有了解如何测试下面的代码 作为起点,我想测试如果.post请求返回a200和b)localStorage`包含来自API调用的令牌,是否调用a)AUTH\u USER 我研究过使用redux mock store、fetch mock和同构fetch来模拟API调用,以确保始终收到预期的API响应,但我不知道从何处开始测试 对于测试起点的任何帮助,我们将不胜感激!即使只是测试200将返

我希望我能就如何测试涉及登录API调用的Redux操作寻求一些帮助。我已经看过一些测试异步操作的示例,但是我还没有了解如何测试下面的代码

作为起点,我想测试如果
.post
请求返回a
200和b)
localStorage`包含来自API调用的令牌,是否调用a)
AUTH\u USER

我研究过使用
redux mock store
fetch mock
同构fetch
来模拟API调用,以确保始终收到预期的API响应,但我不知道从何处开始测试

对于测试起点的任何帮助,我们将不胜感激!即使只是测试
200
将返回
AUTH_USER
的帮助也将不胜感激

注意:对于我正在使用的其他测试,reduxmockstore、enzyme、chai、expect、fetchmock、同构fetch


异步测试动机

我们希望确保,如果登录成功,则由我们的redux thunk中间件发送身份验证成功操作;如果登录失败,则发送身份验证失败操作

请记住,我们不是在测试Redux Thunk中间件,而是在测试Thunk操作创建者

测试查询API的Redux Thunk操作创建者

  • 使用redux thunk中间件为每个单元测试创建一个模拟存储
  • 使用模拟库(如nock)拦截http请求,以测试为给定类型的请求调度哪些操作。因为我们正在测试一个登录请求,所以这里有一些http响应,它们表示登录成功和失败
  • 验证为给定http响应向存储区调度了正确的操作
  • 示例

    测验

    下面是使用nock模拟api调用和expect库进行测试断言的两个登录成功和失败测试的示例

    import configureMockStore from 'redux-mock-store'
    import thunk from 'redux-thunk'
    import nock from 'nock'
    import expect from 'expect' // You can use any testing library
    
    // modify these imports to suit your project
    import * as actions from '../../actions/TodoActions' 
    import * as types from '../../constants/ActionTypes'
    
    import {
      AUTH_USER, AUTH_ERROR
    } from './types';
    
    const API_URL = 'www.api-example.com'
    const middlewares = [ thunk ]
    const mockStore = configureMockStore(middlewares)
    
    describe('async actions', () => {
      afterEach(() => {
        nock.cleanAll()
      })
    
      it('creates AUTH_USER action when user is logged in', () => {
        nock(API_URL)
          .post(/auth/login)
          .reply(200, { data: 'Logged in successfully'] }})
    
        const expectedActions = [
          { type: AUTH_USER }
        ]
        const store = mockStore({ })
    
        return store.dispatch(actions.loginUser({'example@x.com','password'}))
          .then(() => { // return of async actions
            expect(store.getActions()).toEqual(expectedActions)
          })
      })
    
      it('creates AUTH_ERROR if user login fails', () => {
        nock(API_URL)
          .post(/auth/login)
          .reply(404, { data: {error: 404 }] }})
    
        const expectedActions = [
          { type: AUTH_ERROR }
        ]
        const store = mockStore({ })
    
        return store.dispatch(actions.loginUser({'example@x.com','password'}))
          .then(() => { // return of async actions
            expect(store.getActions()).toEqual(expectedActions)
          })
      })
    })
    
    现在,为了使示例生效,您需要在thunk action创建者返回的函数中添加一个return语句

    通过最终返回axios.post给我们的承诺,我们可以添加.然后在测试内部调用,断言在承诺解决后已发送哪些操作

    Thunk动作创建者


    您使用的javascript测试框架是什么?@jaganathanbanthessaran-Enzyme,chai,我认为这是一个很好的开始!我似乎得到了
    TypeError:无法读取
    上未定义的
    的属性'then'。我在
    登录用户
    功能中添加了一个日志,它肯定会从测试中收到电子邮件和密码。有什么想法吗?看我的编辑。您需要回电话给axios.post,它会回复您的承诺。谢谢。我应该使用真实的电子邮件/密码进行此测试吗?目前,我在尝试测试
    200
    登录请求时收到
    错误登录信息
    消息,这并不理想。我认为像
    nock
    这样的库是为了伪造请求,并确保它总是发送您在测试文件中定义的响应。不,没有充分的理由为此测试使用真实密码。请记住,我们正在使用Nock拦截http请求,因此它不知道用户名或密码是否正确。将标记此为正确答案。事实上,我的错误是因为我的问题不够具体。它仍然在
    .catch
    函数中结束,因为我在API调用中使用了
    axios
    ,并且测试是在Chrome/PhantomJS中进行的,所以API调用没有被拾取。我必须安装一个axios模拟库来检测调用。除此之外,答案完美无瑕,因此非常感谢您的帮助。
    import configureMockStore from 'redux-mock-store'
    import thunk from 'redux-thunk'
    import nock from 'nock'
    import expect from 'expect' // You can use any testing library
    
    // modify these imports to suit your project
    import * as actions from '../../actions/TodoActions' 
    import * as types from '../../constants/ActionTypes'
    
    import {
      AUTH_USER, AUTH_ERROR
    } from './types';
    
    const API_URL = 'www.api-example.com'
    const middlewares = [ thunk ]
    const mockStore = configureMockStore(middlewares)
    
    describe('async actions', () => {
      afterEach(() => {
        nock.cleanAll()
      })
    
      it('creates AUTH_USER action when user is logged in', () => {
        nock(API_URL)
          .post(/auth/login)
          .reply(200, { data: 'Logged in successfully'] }})
    
        const expectedActions = [
          { type: AUTH_USER }
        ]
        const store = mockStore({ })
    
        return store.dispatch(actions.loginUser({'example@x.com','password'}))
          .then(() => { // return of async actions
            expect(store.getActions()).toEqual(expectedActions)
          })
      })
    
      it('creates AUTH_ERROR if user login fails', () => {
        nock(API_URL)
          .post(/auth/login)
          .reply(404, { data: {error: 404 }] }})
    
        const expectedActions = [
          { type: AUTH_ERROR }
        ]
        const store = mockStore({ })
    
        return store.dispatch(actions.loginUser({'example@x.com','password'}))
          .then(() => { // return of async actions
            expect(store.getActions()).toEqual(expectedActions)
          })
      })
    })
    
    import axios from 'axios';
    import { browserHistory } from 'react-router';
    import { API_URL } from 'config';
    import {
      AUTH_USER
    } from './types';
    
    export function loginUser({ email, password }) {
      return function (dispatch) {
        return axios.post(`${API_URL}/auth/login`, { email, password })
          .then((response) => {
            dispatch({ type: AUTH_USER });
            localStorage.setItem('token', response.data.token);
            browserHistory.push('/feature');
          })
          .catch(() => {
            dispatch(authError('Bad Login Info'));
          });
      };
    }