我想使用 Jest 和 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 中,我有:
<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: 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 文件作为值?
最佳答案
您可以使用 DataTransfer
来做到这一点。目的。不幸的是,它还没有添加到 JSDOM 中,因此您无法在 Jest 中进行测试。添加对象有一个 Unresolved 问题— https://github.com/jsdom/jsdom/issues/1568
如果您使用 Karma 在浏览器中运行测试,您可以这样测试:
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')
关于unit-testing - 如何使用 Jest 和 vue/test-utils 测试输入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48993134/