开玩笑测试 - 如何处理 JsonWebToken 响应

Posted

技术标签:

【中文标题】开玩笑测试 - 如何处理 JsonWebToken 响应【英文标题】:Jest testing - how to handle JsonWebToken response 【发布时间】:2020-10-23 08:43:54 【问题描述】:

我正在学习如何测试我的 redux thunk 操作,我的登录响应包括一个随机的 JsonWebToken。我编写了一个名为 expectedActions 的变量,它匹配从操作返回的所有数据,除了如何处理随机字符串 (JWT)。关于如何处理这个问题的任何想法?

-- 另外,我需要传递真实的用户信息(用户名/密码)以获得LOGIN_SUCCESS 响应,否则该函数将调度LOGIN_FAIL 操作。这正常吗?

/* eslint-disable no-undef */
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import fetchMock from 'fetch-mock';
import * as actions from '../../../redux/actions/auth';

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

describe('redux async actions', () => 
  afterEach(() => 
    fetchMock.reset();
    fetchMock.restore();
  );

  it('returns expected login response', async () => 
    const userData = 
      username: 'user',
      email: 'user@gmail.com',
      password: 'password',
    ;
    const config = 
      headers: 
        'Content-Type': 'application/json',
      ,
    ;
    fetchMock.getOnce('http://localhost:5000/api/v1/users', 
      body:  ...userData ,
      config,
    );

    const expectedActions =  payload:  token: '' , type: 'LOGIN_SUCCESS' ;
    // the value of the token above in the response is a randomized jwt string

    const store = mockStore();

    return store
      .dispatch(actions.login('user@gmail.com', 'password'))
      .then(() => 
        // return of async actions
        const actionsResponse = store.getActions();
        expect(actionsResponse[0]).toEqual(expectedActions);
      );
  );
);

奖励:fetchMock 有什么意义?我从另一个 *** 问题中借用了上面的代码,但我还没有理解 fetchMock 在做什么。

【问题讨论】:

【参考方案1】:

我用自己的令牌“123”覆盖了响应 JWT。不过我不知道这是否正确,我也不期待这篇文章得到回应。

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

describe('redux async actions', () => 
  afterEach(() => 
    fetchMock.reset();
    fetchMock.restore();
  );

  it('returns expected login response', async () => 
    const expectedActions = 
      payload:  token: '123' ,
      type: 'LOGIN_SUCCESS',
    ;

    const store = mockStore( alert: [], auth:  token: '123'  );

    return store
      .dispatch(actions.login('user@gmail.com', 'somePassword'))
      .then(() => 
        // return of async actions
        const actionsResponse = store.getActions();
        actionsResponse[0].payload.token = '123';
        expect(actionsResponse[0]).toEqual(expectedActions);
      );
  );
);

【讨论】:

以上是关于开玩笑测试 - 如何处理 JsonWebToken 响应的主要内容,如果未能解决你的问题,请参考以下文章

使用mockmvc测试如何处理无序数组

单元测试时如何处理 API 调用速率限制?

Mandrill 在测试模式下如何处理附件?

Xcode UI测试如何处理UNUserNotificationCenter生成的通知权限

kapt:如何处理测试源?

如何处理 TDD 的重构阶段