簡體   English   中英

開玩笑測試 - 如何處理 JsonWebToken 響應

[英]Jest testing - how to handle JsonWebToken response

我正在學習如何測試我的 redux thunk 操作,我的登錄響應包括一個隨機的 JsonWebToken。 我編寫了一個名為expectedActions的變量,它匹配從操作返回的所有數據,除了如何處理隨機字符串 (JWT)。 關於如何處理這個問題的任何想法?

-- 另外,我需要傳遞真實的用戶信息(用戶名/密碼)以獲得LOGIN_SUCCESS響應,否則 function 會調度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什么意義? 我從另一個 StackOverflow 問題中借用了上面的代碼,但我還沒有理解 fetchMock 在做什么。

我用自己的令牌“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);
      });
  });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM