gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 13:45:54 25 4
gpt4 key购买 nike

我是 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:"a@a.com",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 测试输出

● 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"]
}

最佳答案

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

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

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

在上面的代码中

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

确保 thunk 捕获错误

关于reactjs - React Jest 创建错误 "new Error(' .. .')"立即退出并失败测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45286749/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com