【发布时间】:2021-09-15 11:36:29
【问题描述】:
我正在尝试测试一个包含 FileReader 的 Vue 组件的方法。我需要读取一个 json 文件。
方法:
readConfig(event) {
this.config.headers = [];
this.config.keys = [];
this.config.rules = [];
this.columns = 0
const fr = new FileReader();
fr.onload = e => {
const result = JSON.parse(e.target.result);
this.config.connectionType = result.connection.type;
this.config.url = result.connection.url;
if(result.connection.type === 'rest') {
this.config.api = result.connection.api;
this.config.time = result.connection.time;
} else {
this.config.socket = result.connection.socket;
}
result.table.headers.forEach((el, index) => {
this.addElement();
this.config.headers[index] = el;
this.config.keys[index] = result.table.keys[index];
})
this.config.rules = result.table.rules;
}
fr.readAsText(event.target.files.item(0));
}
由这个输入文件调用:
<input v-if="!saved" type="file" @change="readConfig" accept=".json">
我尝试遵循一些解决方案,但无法上传以加载我的 json 提前致谢
【问题讨论】:
-
刚刚测试过。我有这个错误模拟(...)不是函数
-
答案是 React 和 Enzyme。您需要相应地调整特定于 Vue 测试工具的部分。涉及到 Filereader 的部分也是一样。
-
现在我可以输入 fr.onload 但 JSON.parse 总是返回“位置 1 的 JSON 中的意外标记 o”。这个电话正确吗? reader.onload ({target: {result: {"connection": {"type": "rest", "url": "http://localhost: 3000", "api": "/", "time": 3}}},文件:[{name: 'config.json', size: '20000', type: 'text/json'}]});
-
该错误表示在预期 JSON 字符串的位置提供了一个对象 stackoverflow.com/questions/43612837/… 。
result应该是一个字符串。
标签: javascript vue.js jestjs