[英]Jest with jsdom, document is undefined inside Promise resolve
場景
嘗試使用Jest(和酶)測試一個簡單的React組件。 這個組件使用react-dropzone
,我想測試一些涉及DOM的操作,所以我使用jsdom(已經由create-react-app
配置)
問題
在我的測試代碼中可用的document
對象,以及在組件內部可用的document
對象,在dropzone onDrop
回調內部均未undefined
,從而阻止了測試的運行。
代碼
MyDropzone
import React from 'react'
import Dropzone from 'react-dropzone'
const MyDropzone = () => {
const onDrop = ( files ) =>{
fileToBase64({file: files[0]})
.then(base64Url => {
return resizeBase64Img({base64Url})
})
.then( resizedURL => {
console.log(resizedURL.substr(0, 50))
})
}
return (
<div>
<Dropzone onDrop={onDrop}>
Some text
</Dropzone>
</div>
);
};
const fileToBase64 = ({file}) => {
return new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onload = () => {
return resolve(reader.result)
}
reader.onerror = (error) => {
return reject(error)
}
reader.readAsDataURL(file)
})
}
/**
* Resize base64 image to width and height,
* keeping the original image proportions
* with the width winning over the height
*
*/
const resizeBase64Img = ({base64Url, width = 50}) => {
const canvas = document.createElement('canvas')
canvas.width = width
const context = canvas.getContext('2d')
const img = new Image()
return new Promise((resolve, reject) => {
img.onload = () => {
const imgH = img.height
const imgW = img.width
const ratio = imgW / imgH
canvas.height = width / ratio
context.scale(canvas.width / imgW, canvas.height / imgH)
context.drawImage(img, 0, 0)
resolve(canvas.toDataURL())
}
img.onerror = (error) => {
reject(error)
}
img.src = base64Url
})
}
export default MyDropzone;
MyDropzone.test.jsx
import React from 'react'
import { mount } from 'enzyme'
import Dropzone from 'react-dropzone'
import MyDropzone from '../MyDropzone'
describe('DropzoneInput component', () => {
it('Mounts', () => {
const comp = mount(<MyDropzone />)
const dz = comp.find(Dropzone)
const file = new File([''], 'testfile.jpg')
console.log(document)
dz.props().onDrop([file])
})
})
setupJest.js
import { configure } from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'
configure({ adapter: new Adapter() })
設定檔
create-react-app
jest配置,其中setupJest.js
添加到setupFiles
錯誤
TypeError: Cannot read property 'createElement' of undefined
at resizeBase64Img (C:\dev\html\sandbox\src\MyDropzone.jsx:44:29)
at fileToBase64.then.base64Url (C:\dev\html\sandbox\src\MyDropzone.jsx:8:20)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
更多信息
考慮到如果在瀏覽器中運行該代碼,則始終會定義該document
,因此對我而言,該問題似乎與jsdom或Jest有關。
我不確定它是否與Promises,FileReaded或JS范圍有關。
也許是玩笑方面的錯誤?
所以我能夠解決這個問題。 假設它無需任何配置更改即可工作的說法是錯誤的。 首先,您需要添加一些其他軟件包。 以下是我更新的package.json
{
"name": "js-cra",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "^16.3.2",
"react-dom": "^16.3.2",
"react-dropzone": "^4.2.9",
"react-scripts": "1.1.4",
"react-test-renderer": "^16.3.2"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"devDependencies": {
"enzyme": "^3.3.0",
"enzyme-adapter-react-16": "^1.1.1",
"jest-enzyme": "^6.0.0",
"jsdom": "11.10.0",
"jsdom-global": "3.0.2"
}
}
我也從測試腳本中刪除了--env=jsdom
。 因為我無法使其與該組合一起使用
之后,您需要創建一個src/setupTests.js
,它是測試的全局負載。 這是您需要加載jsdom
和enzyme
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import 'jest-enzyme';
import 'jsdom-global/register'; //at the top of file , even , before importing react
configure({ adapter: new Adapter() });
之后,您的測試將出錯並出現以下錯誤
/Users/tarun.lalwani/Desktop/tarunlalwani.com/tarunlalwani/workshop/ub16/so/jsdom-js-demo/node_modules/react-scripts/scripts/test.js:20
throw err;
^
ReferenceError: FileReader is not defined
問題似乎是FileReader
應該使用window
范圍引用。 所以你需要像下面這樣更新
const reader = new window.FileReader()
然后再次運行測試
現在測試工作正常
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.