如何使用 Jest 和 vue/test-utils 测试输入文件 [英] How to test input file with Jest and vue/test-utils
问题描述
我想使用 Jest 和 vue/test-utils 测试文件上传组件.
I want to test file uploader component using Jest and vue/test-utils.
我有这个:
describe('show progress bar of uploading file', () => {
const wrapper = mount(FileUploaderComponent)
// create csv file
let csv = new Blob([''], { type: 'text/csv;charset=utf-8;' })
csv.name = 'myFile.csv'
let input = wrapper.find('input')
input.element.value = csv // || csv.error value, Error here
input.trigger('change')
// Update current status
})
我在 FileUploaderComponent 中的位置:
Where in FileUploaderComponent i have:
<template>
<form action="POST" enctype="multipart/form-data">
<label class="btn btn-primary" for="input-file">
<input class="input-file" id="input-file" name="file" type="file" accept=".xlsx, .xls, .csv">
UPLOAD FILE
</label>
</form>
</template>
抛出这个错误:
InvalidStateError: 这个输入元素接受一个文件名,它可能只能以编程方式设置为空字符串.
InvalidStateError: This input element accepts a filename, which may only be programmatically set to the empty string.
49 |
50 | let input = wrapper.find('input')
> 51 | input.element.value = csv
52 | input.trigger('change')
53 |
54 | // Update current status
那么,问题是:如何使用文件输入值触发事件更改?在这种情况下,一个 csv 文件作为值?
So, the question is: How can i trigger event change with file input value? in this case, a csv file as value ?
推荐答案
您可以使用 DataTransfer
对象执行此操作.不幸的是,它还没有添加到 JSDOM 中,因此您无法在 Jest 中进行测试.添加对象有一个未解决的问题——https://github.com/jsdom/jsdom/issues/1568
You could do this using the DataTransfer
object. Unfortunately, it hasn't been added to JSDOM, so you can't test in Jest. There's an open issue to add the object—https://github.com/jsdom/jsdom/issues/1568
如果您使用 Karma 在浏览器中运行测试,您可以这样测试:
If you ran your tests in a browser using Karma, you could test like this:
const wrapper = shallow(FormComponent)
const input = wrapper.find('input[type="file"]')
const dT = new ClipboardEvent('').clipboardData || new DataTransfer()
dT.items.add(new File(['foo'], 'programmatically_created.txt'))
input.element.files = dT.files
input.trigger('change')
这篇关于如何使用 Jest 和 vue/test-utils 测试输入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!