为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕斯709654 2022-05-22 10:22:06
我试图在失败时测试我的行为。调用 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))那么我该如何测试那部分呢?
查看完整描述

2 回答

?
猛跑小猪

TA贡献1858条经验 获得超8个赞

在您的情况下,它与正面测试相同:您需要模拟ApiService.getTips,因此它会称为“正面反馈”或“负面反馈”。说,现在你没有测试成功fetchTips时调度的动作getTips。


这将是相似的(没有打字稿):


it('dispatches loadTips on success', () => {

  const mockedResponse = [1,2,3];

  ApiService.getTips.mockImplementation(

    (successCallback, failureCallback) => successCallback(mockedResponse)

  );

  store.dispatch(actions.fetchTips());

  expect(store.getActions()).toContainEqual(actions.loadTips(mockedResponse));

  expect(store.getActions()).not.toContainEqual(

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

  );

});


it('dispatches toast message on failure', () => {

  ApiService.getTips.mockImplementation(

    (successCallback, failureCallback) => failureCallback()

  );

  store.dispatch(actions.fetchTips());

  expect(store.getActions()).toContainEqual(

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

  );

  expect(store.getActions()).not.toContainEqual(actions.loadTips(mockedResponse));

});


查看完整回答
反对 回复 2022-05-22
?
梵蒂冈之花

TA贡献1900条经验 获得超5个赞

由于这是负面测试,您必须使用负面数据调用 api。检查 ApiService.getTips 的实现并抛出错误。或模拟 ApiService.getTips 并抛出错误(调用错误回调)


ApiService.getTips(

    tips => dispatch(loadTips(tips)),

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

  )


查看完整回答
反对 回复 2022-05-22
  • 2 回答
  • 0 关注
  • 119 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信