如何测试测试中的负面行为?就像调用 API 失败一样

我试图在失败时测试我的行为。调用 API 的操作。


我有这个:


export const loadTips = (tips: TipsModel): LoadTips => ({ tips, type: LOAD_TIPS });


export const fetchTips: ActionCreator<ThunkType> = () => async (dispatch) => {

  return ApiService.getTips(

    tips => dispatch(loadTips(tips)),

    () => dispatch(triggerToast('Tips are not loading. Try again later!', true))

  );

};

这些是我到目前为止正确通过的测试:


import * as actions from './tipsActions';

import { LOAD_TIPS, LoadTips, CLEAR_TIPS, ClearTips, DisableOrSnoozedTips, DISABLE_SNOOZ_TIP } from '../types/tipsTypes';

import getStore from '../services/mockGlobalStore';

import { mocked } from 'ts-jest/utils';

import ApiService from '../services/apiService';


jest.mock('../services/apiService');

const mockedApiService = mocked(ApiService, true);


describe('tips actions on API', () => {

  beforeEach(() => {

    mockedApiService.mockClear();

  });


  const store = getStore();


  it('fetchTips makes API call', () => {

    store.dispatch(actions.fetchTips());


    expect(mockedApiService.getTips).toHaveBeenCalledWith(expect.any(Function), expect.any(Function));

  });

});


describe('tips actions', () => {

  it('creates a loadTips action', () => {

    const expectedAction: LoadTips = { type: LOAD_TIPS, tips: dummyTips };


    expect(actions.loadTips(dummyTips)).toEqual(expectedAction);

  });

});


所以我想知道我可以做些什么来测试,例如当动作失败时它会分派动作:


dispatch(triggerToast('Tips are not loading. Try again later!', true))

那么我该如何测试那部分呢?


慕斯709654
浏览 120回答 2
2回答

猛跑小猪

在您的情况下,它与正面测试相同:您需要模拟ApiService.getTips,因此它会称为“正面反馈”或“负面反馈”。说,现在你没有测试成功fetchTips时调度的动作getTips。这将是相似的(没有打字稿):it('dispatches loadTips on success', () => {&nbsp; const mockedResponse = [1,2,3];&nbsp; ApiService.getTips.mockImplementation(&nbsp; &nbsp; (successCallback, failureCallback) => successCallback(mockedResponse)&nbsp; );&nbsp; store.dispatch(actions.fetchTips());&nbsp; expect(store.getActions()).toContainEqual(actions.loadTips(mockedResponse));&nbsp; expect(store.getActions()).not.toContainEqual(&nbsp; &nbsp; triggerToast('Tips are not loading. Try again later!', true)&nbsp; );});it('dispatches toast message on failure', () => {&nbsp; ApiService.getTips.mockImplementation(&nbsp; &nbsp; (successCallback, failureCallback) => failureCallback()&nbsp; );&nbsp; store.dispatch(actions.fetchTips());&nbsp; expect(store.getActions()).toContainEqual(&nbsp; &nbsp; triggerToast('Tips are not loading. Try again later!', true)&nbsp; );&nbsp; expect(store.getActions()).not.toContainEqual(actions.loadTips(mockedResponse));});

梵蒂冈之花

由于这是负面测试,您必须使用负面数据调用 api。检查 ApiService.getTips 的实现并抛出错误。或模拟 ApiService.getTips 并抛出错误(调用错误回调)ApiService.getTips(&nbsp; &nbsp; tips => dispatch(loadTips(tips)),&nbsp; &nbsp; () => dispatch(triggerToast('Tips are not loading. Try again later!', true))&nbsp; )
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript