这是我要测试的代码:
onDrop(acceptedFiles) {
const upload = (file) => {
fetch(url, {
method: 'POST',
headers: this.props.headers,
body: file,
}).then((res) => {
if (!res.ok) {
this.setState({ fileName: '' });
} else {
res.json()
.then((result) => {
this.setState({
fileName: '',
total: `Total: ${result.total}`,
failures: `Failures: ${result.failures}`,
result: result.output,
});
});
}
}).catch((error) => {
const result = { body: error, status: 500 };
this.setState({ fileName: '' });
});
};
render() {
let dz = '';
if (this.state.fileName === '') {
dz = (
<Dropzone onDrop={files => this.onDrop(files)}></Dropzone>
);
}
return (
<div>
{dz}
<p>{this.state.total}<br />{this.state.failures}<br />{this.state.result}</p>
</div>
);
}
这是我编写的测试,当我运行所有测试时通过,但是当我仅运行此测试或仅包含测试的文件时崩溃。
describe('FileUpload', () => {
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<FileUpload headers={headers} />, div);
expect(div).toMatchSnapshot();
});
});
命令行显示:
C:\Users\path\node_modules\react-scripts\scripts\test.js:20
throw err;
^
TypeError: Network request failed
at XMLHttpRequest.xhr.onerror (C:\Users\path\node_modules\whatwg-fetch\fetch.js:436:16)
at XMLHttpRequest.callback.(anonymous function) (C:\Users\path\node_modules\react-scripts\node_modules\jsdom\lib\jsdom\living\events\EventTarget-impl.js:289:32)
at invokeEventListeners (C:\Users\path\node_modules\react-scripts\node_modules\jsdom\lib\jsdom\living\events\EventTarget-impl.js:219:27)
at invokeInlineListeners (C:\Users\path\node_modules\react-scripts\node_modules\jsdom\lib\jsdom\living\events\EventTarget-impl.js:166:7)
at EventTargetImpl._dispatch (C:\Users\path\node_modules\react-scripts\node_modules\jsdom\lib\jsdom\living\events\EventTarget-impl.js:122:7)
at EventTargetImpl.dispatchEvent (C:\Users\path\node_modules\react-scripts\node_modules\jsdom\lib\jsdom\living\events\EventTarget-impl.js:87:17)
at XMLHttpRequest.dispatchEvent (C:\Users\path\node_modules\react-scripts\node_modules\jsdom\lib\jsdom\living\generated\EventTarget.js:61:35)
at XMLHttpRequest.abort (C:\Users\path\node_modules\react-scripts\node_modules\jsdom\lib\jsdom\living\xmlhttprequest.js:405:16)
at Object.abort (C:\Users\path\node_modules\react-scripts\node_modules\jsdom\lib\jsdom\living\xhr-utils.js:315:13)
at RequestManager.close (C:\Users\path\node_modules\react-scripts\node_modules\jsdom\lib\jsdom\living\nodes\Document-impl.js:146:21)
at Window.close (C:\Users\path\node_modules\react-scripts\node_modules\jsdom\lib\jsdom\browser\Window.js:362:29)
at JSDOMEnvironment.dispose (C:\Users\path\frontend\node_modules\react-scripts\node_modules\jest-environment-jsdom\build\index.js:44:19)
at Promise.resolve.then (C:\Users\path\node_modules\react-scripts\node_modules\jest\node_modules\jest-cli\build\runTest.js:102:17)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
npm ERR! Test failed. See above for more details.
我知道由于渲染功能中的获取(使用POST)而导致测试崩溃,但是我还有其他通过渲染功能中的使用获取(带有GET)的测试。任何帮助/建议将不胜感激。