[英]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. 我有一个具有
handleChange
方法的React组件。 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. 我的困境是我想监视在此设置的onload函数,但这些函数是在运行时设置的。
I have spent some time mocking out FileReader and Image but can't wrap my head around this. 我花了一些时间来模拟FileReader和Image,但是无法解决这个问题。
How can I achieve this with Jest? 我如何用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: 如何接受FileReader作为参数,以便您可以在单元测试中创建自己的产品,对其进行监视,然后将其作为参数传递,如下所示:
Modify your handleChange function to accept a FileReader as a parameter, which is created automatically if none is passed: 修改handleChange函数以接受FileReader作为参数,如果未传递任何参数,则会自动创建它:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.