Testing catch block via jest mock

jest test promise catch block
jest mock request
jasmine test catch block
jest unhandledpromiserejectionwarning
matcher error: received value must be a promise
jest spyon async function
jest try catch (error)
jest wait for mock to be called

I'm trying to test the 'catch' block of an async redux action via jest, but throwing a catch in the mock causes the test as a whole to fail.

My action is as follows:

export function loginUser(username, password) {
  return async dispatch => {
    dispatch({type: UPDATE_IN_PROGRESS});
    try {
      let response = await MyRequest.postAsync(
        '/login', {username: username, password: password}
      );
      dispatch({
        type: USER_AUTHENTICATED,
        username: response.username,
        token: response.token,
        role: response.role,
        id: response.id
      });
    } catch (error) {
      dispatch({type: USER_SIGNED_OUT});
      throw error;
    } finally {
      dispatch({type: UPDATE_COMPLETE});
    }
  };
}

The test is trying to mock up 'MyRequest.postAsync' to throw an error and thus trigger the catch block, but the test just bails with a 'Failed' message

it('calls expected actions when failed log in', async() => {
  MyRequest.postAsync = jest.fn(() => {
    throw 'error';
  });

  let expectedActions = [
    {type: UPDATE_IN_PROGRESS},
    {type: USER_SIGNED_OUT},
    {type: UPDATE_COMPLETE}
  ];

  await store.dispatch(userActions.loginUser('foo', 'bar'));
  expect(store.getActions()).toEqual(expectedActions);
});

Is there a way to trigger the catch block to execute in my test via a jest mock function (or any other way for that matter)? Would be annoying to not be able to test a large chunk of code (as all my requests work in the same way).

Thanks in advance for help with this.

I had the same issue. For me the below works. Wrapping up the await with a try/catch

  it('calls expected actions when failed log in', async() => {
  MyRequest.postAsync = jest.fn(() => {
    throw 'error';
  });

  let expectedActions = [
    {type: UPDATE_IN_PROGRESS},
    {type: USER_SIGNED_OUT},
    {type: UPDATE_COMPLETE}
  ];
  try {
     await store.dispatch(userActions.loginUser('foo', 'bar'));
  } catch(e) {
     expect(store.getActions()).toEqual(expectedActions);
  }

});

An Async Example · Jest, This module is being mocked in __mocks__/request.js http.get({path: url}, response Testing for async errors using Promise.catch. it('tests error with promises',  Configuring the Testing Framework. To install jest run yarn add --dev jest (if you're using Expo you could alternatively use jest-expo). Then, in your package.json, you'll want to configure jest by adding the following. package.json

I don't know if it's still relevant, but you can do it in this way:

it('tests error with async/await', async () => {
  expect.assertions(1);
  try {
    await store.dispatch(userActions.loginUser('foo', 'bar'));
  } catch (e) {
    expect(e).toEqual({
      error: 'error',
    });
  }
});

Here is a documentation about error handling

How to test my logic with a try catch block · Issue #3 · jeffbski/redux , I want to test the onErrorLoginRequest in a try catch block. Unhandled promise rejection (rejection id: 1): Error: expect(jest.fn()). probably just always reset (by recreating the store using createMockStore) the store for every  Testing Asynchronous Code It's common in JavaScript for code to run asynchronously. When you have code that runs asynchronously, Jest needs to know when the code it is testing has completed, before it can move on to another test.

I set the instance variable which we will access in our testing function to undefined so that it will go to catch block.

PS : This might not be possible all the times as we might not be having variables all time

class APIStore {

 async fetchProductsAPI() {
    try {
       const products =  networkManager.fetch('products')
       this.productsStore.setProducts(prodcuts)
    } 
    catch(e) {
       this.apiStatus = API_FAILED
       this.apiError = e
    }
  }
}

Test case

it('Check API Error ', async () => {

    const toCheckErrorStore = new APIStore()

    // Setting products store to undefined so that execution goes to catch block
    toCheckErrorStore.productsStore = undefined

    await toCheckErrorStore.fetchProductsAPI()

    expect(toCheckErrorStore.apiStatus).toBe(API_FAILED)
    expect(toCheckErrorStore.apiError).toEqual(errorObjectIWantToCompareWith)
}

Jest - test try-catch block, I'm trying to test a try catch block using Jest. E.g. // filename: toHaveBeenCalled​() // throwing error //jest.fn() value must be a mock function or spy. }) If it's b that  Here we enable fake timers by calling jest.useFakeTimers();. This mocks out setTimeout and other timer functions with mock functions. If running multiple tests inside of one file or describe block, jest.useFakeTimers(); can be called before each test manually or with a setup function such as beforeEach. Not doing so will result in the internal

Why isn't this unit test catching an error from this async/await , When you're writing unit tests for asynchronous functions in JavaScript, one test path/to/fn') describe('#fetchItem', () => { it('should catch an error', async () => { await Chai will wait for Promises, so instead of using await Better solution would be to wrap it in try catch block and test error that is caught. Mock functions make it easy to test the links between code by erasing the actual implementation of a function, capturing calls to the function (and the parameters passed in those calls), capturing instances of constructor functions when instantiated with new, and allowing test-time configuration of return values.

Testing JavaScript's Fetch with Jest, /__tests__/connectivity/async-fetch.js const fetchMock = require('fetch-mock'); import asyncFetch from '. I found this via a GitHub ticket for the Jest project. and either return a function which returns the outcome, or will catch and re-throw the exception. 32, Change Password - Part 6 - Avoid Blocking, and Wrap Up, 06:23. An Async Example First, enable Babel support in Jest as documented in the Getting Started guide. Let's implement a module that fetches user data from an API and returns the user name.

Jest explicitly or arbitrarily force fail() a test · Code with Hugo, When testing code with Jest, it can sometimes be useful to fail a test arbitrarily. This post goes through a few scenarios where that might be useful. What we need to do is to make sure the try block doesn't continue executing throw] 8 | throw new Error("didn't throw"); 9 | } catch (error) { > 10 | expect(error). Jest uses a custom resolver for imports in your tests making it simple to mock any object outside of your test’s scope. You can use mocked imports with the rich Mock Functions API to spy on function calls with readable test syntax.

Comments
  • To you use jest.mock to mock MyRequest, otherwise it will not work
  • Sorry @AndreasKöberle could you elaborate slightly please? Using jest.fn() seems to work fine to mock a function on an imported module, it's the throw 'error' that's causing an issue
  • Maybe it the throw in the catch block then