用jsdom开玩笑,文档在Promise解析中未定义

sti*_*ife 10 javascript jsdom reactjs jestjs enzyme

场景

尝试使用Jest(和Enzyme)测试一个简单的React组件.这个组件使用react-dropzone,我想测试一些涉及DOM的操作,所以我使用jsdom(已经配置create-react-app)

问题

document在我的测试代码中可用但在组件内部可用的对象undefined位于dropzone onDrop回调内部,这会阻止测试运行.

代码

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;
Run Code Online (Sandbox Code Playgroud)

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])
    })
})
Run Code Online (Sandbox Code Playgroud)

setupJest.js

import { configure } from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'

configure({ adapter: new Adapter() })
Run Code Online (Sandbox Code Playgroud)

配置

  • 添加到的默认create-react-appjest配置setupJest.jssetupFiles
  • 运行:纱线测试

错误

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)
Run Code Online (Sandbox Code Playgroud)

更多信息

document如果在浏览器中运行该代码,则始终定义,因此对我来说问题似乎与jsdom或Jest有关.

我不确定它是否与Promise,FileReaded或JS范围有关.

可能是Jest方面的一个错误?

Tar*_*ani 6

所以我能够解决这个问题.假设它在没有任何配置更改的情况下工作是错误的.首先,您需要添加更多包.以下是我的更新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"
  }
}
Run Code Online (Sandbox Code Playgroud)

我也--env=jsdom从测试脚本中删除了.因为我无法使用这种组合

之后,您需要创建一个src/setupTests.js,这是测试的加载全局变量.这是你需要加载jsdomenzyme

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() });
Run Code Online (Sandbox Code Playgroud)

之后,您的测试会出错并出现以下错误

/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
Run Code Online (Sandbox Code Playgroud)

这个问题似乎FileReader应该与window范围一起提及.所以你需要像下面这样更新它

const reader = new window.FileReader()
Run Code Online (Sandbox Code Playgroud)

然后再次运行测试

工作测试

现在测试工作正常