Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Jest creating error "new Error('...')" exit and fail testing immediately

Tags:

reactjs

jestjs

I'm new to Jest and React and is setting up Jest unit test for the React web project and encounter this problem when I'm trying to do it on async dispatch. Whenever there is a new Error(...), the test case just exits and fails when execute that line. (It starts with the test case run to jest-jasmine2 module where it has a new Error in execution. Then I try new Error in my test case directly and it fails too...). When npm start, nothing wrong happen, but only when npm test, this happens.

./__TEST__/action.test.js

import * as actions from '../actions';
import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'

const middlewares = [ thunk ];
const mockStore = configureMockStore(middlewares);


describe('signIn dispatch action',()=>{
let store
beforeEach(()=>{
    store = mockStore({})
    window.fetch =jest.fn()
})
it('successful2 login', async ()=>{
    const response = '{...}'
    window.fetch.mockImplementationOnce (
        () => Promise.resolve({json: () => Promise.resolve(JSON.parse(response))})
    );
    await store.dispatch(actions.signIn({email:"[email protected]",password:"123"}))
})

it('fail login', () => {

    window.fetch =jest.fn()
    const error = new Error("blahblahblah")
    window.fetch.mockImplementationOnce(
        () => Promise.reject(error)
    );
    return store.dispatch(actions.signIn({email: "", password: ""}, onSuccess))
        .then(() => {
        })
})
})

npm test output

● signIn dispatch action › successful2 login

Failed: [object Object]

  at stackFormatter (node_modules/jest-jasmine2/build/expectationResultFactory.js:30:20)
  at process._tickCallback (internal/process/next_tick.js:109:7)

● signIn dispatch action › fail login

blahblahblah

  at Object.it (src/actions/__test__/actions.test.js:117:23)
  at Promise.resolve.then.el (node_modules/p-map/index.js:42:16)
  at process._tickCallback (internal/process/next_tick.js:109:7)

package.json

"devDependencies": {
"babel-jest": "^20.0.3",
"babel-plugin-transform-es2015-modules-commonjs": "^6.24.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-0": "^6.24.1",
"babel-preset-stage-2": "^6.24.1",
"enzyme": "^2.9.1",
"enzyme-to-json": "^1.5.1",
"jest": "^20.0.4",
"jest-immutable-matchers": "^1.5.0",
"react-addons-test-utils": "^15.6.0",
"react-dom": "^15.6.1",
"react-scripts": "^1.0.10",
"react-test-renderer": "^15.6.1",
"redux-devtools": "^3.3.1",
"redux-devtools-dock-monitor": "^1.1.1",
"redux-devtools-log-monitor": "^1.1.1",
"redux-mock-store": "^1.2.3"
},

.babelrc

{
"presets":["react","es2015","stage-0","stage-2"]
}
like image 640
Mark Chen Avatar asked Jul 24 '17 17:07

Mark Chen


People also ask

How do you force fail a Jest test?

Jest actually uses Jasmine, so you can use fail just like before. Sample call: fail('it should not reach here');

How do I test error in Jest?

Try-catch idiom (better) assertions which verifies that a certain number of assertions are called during a test: it('throws an error when first argument is `null`', () => { expect. assertions(1); try { samePasswordsValidator(null, "bar"); } catch (error) { expect(error. message).

How do you throw an exception in Jest?

Writing a unit test to expect an async function to throw an exception can be done as follows. First we define the async function in a module, then in the test code we use the rejects property to test for any thrown errors. Essentially, we are asserting that our function causes a promise rejection.

How do I set Jest timeout?

For Jest 24.9+, you can also set the timeout from the command line by adding --testTimeout . Default timeout of a test in milliseconds. Default value: 5000.


1 Answers

I know this question is 8 month old. If you still need it, or anyone who stumbles upon this question:

I have seen the same issue in my test when I try to create my custom error. It turns out that it's because my test case is failing, Jest points out both the failing test case and also where the error is created.

Make sure your test doesn't throw the error object you created, and make sure you catch that when that happens.

In the code above

window.fetch.mockImplementationOnce(
        () => Promise.reject(error)
    );

Make sure the thunk catches the error

like image 157
Yiou Avatar answered Oct 02 '22 22:10

Yiou