简体   繁体   中英

How to spy on es6 class methods that are set at run time using Jest

I have a React component that has a handleChange method. This method is roughly as follows:

handleChange({ target }) {
        const [file] = target.files
        const urlReader = new FileReader()
        urlReader.onload = (event) => {
            const canvas = this.canvas
            const image = new Image()
            image.onload = () => {
                draw(image, canvas)   
            }
            image.src = event.target.result
        }
        urlReader.readAsDataURL(file)
}

My dilemma is that I want to spy on the onload functions that are set in this but they are set at run time.

I have spent some time mocking out FileReader and Image but can't wrap my head around this.

How can I achieve this with Jest?

How about accepting the FileReader as a parameter, so that you can then create your own in the unit test, spy on it, and then pass it as a parameter like so:

Modify your handleChange function to accept a FileReader as a parameter, which is created automatically if none is passed:

handleChange({ target }, urlReader = new FileReader()) {
        const [file] = target.files
        urlReader.onload = (event) => {
            const canvas = this.canvas
            const image = new Image()
            image.onload = () => {
                draw(image, canvas)   
            }
            image.src = event.target.result
        }
        urlReader.readAsDataURL(file)
}

In the unit test, you will have something like this (you might need to change some syntax) :

const urlReader = new FileReader()
const urlReaderSpy = jest.spyOn(urlReader, 'onLoad')

handleChange(event, urlReader)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM