开发者问题收集

React Jest 创建错误“new Error('...')”退出并立即测试失败

2017-07-24
4519

我是 Jest 和 React 的新手,正在为 React Web 项目设置 Jest 单元测试,当我尝试在异步调度上执行此操作时遇到此问题。每当出现新的 Error(...) 时,测试用例就会退出并在执行该行时失败。(它从测试用例运行到 jest-jasmine2 模块开始,在执行过程中出现新的错误。然后我直接在测试用例中尝试新的错误,它也失败了...)。当 npm start 时,没有发生任何错误,但只有当 npm test 时,才会发生这种情况。

./__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"]
}
1个回答

我知道这个问题已经存在 8 个月了。如果您仍然需要它,或者任何偶然发现这个问题的人:

当我尝试创建自定义错误时,我在测试中看到了同样的问题。事实证明,这是因为我的测试用例失败了,Jest 指出了失败的测试用例以及错误产生的位置。

确保您的测试不会抛出您创建的错误对象,并确保在发生这种情况时捕获它。

在上面的代码中

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

确保 thunk 捕获错误

Yiou
2018-04-11