selimppc

React API jest test for error handling

Sep 28th, 2020
617
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import React from 'react';
  2. import { shallow } from 'enzyme';
  3. import Dashboard from './Dashboard';
  4. import moxios from 'moxios';
  5.  
  6. describe('111', () => {
  7.   const errorMsg = 'Group already exist';
  8.  
  9.   const event = {
  10.     preventDefault: () => {},
  11.     target: {
  12.       group: '',
  13.       country: ''
  14.     }
  15.   };
  16.   beforeEach(() => {
  17.     moxios.install();
  18.     moxios.stubRequest('/api/dashboard', {
  19.       status: 400,
  20.       response: {
  21.         message: errorMsg
  22.       }
  23.     });
  24.   });
  25.  
  26.   afterEach(() => {
  27.     moxios.uninstall();
  28.   });
  29.  
  30.   it('(await for a method) should set error state when dashboard api returns error', async () => {
  31.     const wrapper = shallow(<Dashboard />);
  32.     await wrapper.instance().onFormSubmit(event);
  33.     expect(wrapper.state('error')).toBe(errorMsg);
  34.   });
  35.  
  36.   it(
  37.     '(promise) should set error state when dashboard api returns error',
  38.     () => {
  39.       const wrapper = shallow(<Dashboard />);
  40.       wrapper.find('form').simulate('submit', event);
  41.       return new Promise(resolve =>
  42.         setImmediate(() => {
  43.           expect(wrapper.state('error')).toBe(errorMsg);
  44.           resolve();
  45.         })
  46.       );
  47.     },
  48.     1000
  49.   );
  50.   it('(await tick) should set error state when dashboard api returns error', async () => {
  51.     const wrapper = shallow(<Dashboard />);
  52.     wrapper.find('form').simulate('submit', event);
  53.     await tick();
  54.     expect(wrapper.state('error')).toBe(errorMsg);
  55.   });
  56.  
  57.   it('(done) should set error state when dashboard api returns error', done => {
  58.     const wrapper = shallow(<Dashboard />);
  59.     wrapper.find('form').simulate('submit', event);
  60.     setImmediate(() => {
  61.       expect(wrapper.state('error')).toBe(errorMsg);
  62.       done();
  63.     });
  64.   });
  65. });
  66.  
  67. function tick() {
  68.   return new Promise(resolve => {
  69.     setTimeout(resolve, 1);
  70.   });
  71. }
Add Comment
Please, Sign In to add comment