【问题标题】:How test a FileReader to read a json file with Jest?如何测试 FileReader 以使用 Jest 读取 json 文件?
【发布时间】: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


【解决方案1】:

感谢您的帮助。 我找到了解决问题的方法

    test('Upload rest configuration', () => {
        // @ts-ignore
        jest.spyOn(global, 'FileReader').mockImplementation(function () {
            // @ts-ignore
            this.readAsText = jest.fn();
        });
        wrapper.find('input[type="file"]').trigger('change');
        // @ts-ignore
        let reader = FileReader.mock.instances[0];
        reader.onload({ target: { result: JSON.stringify(config) }, files: [{name: 'config.json', size:'20000', type:'text/json'}] });

    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-04
    • 2020-06-16
    • 2014-01-18
    • 2012-09-04
    • 2018-03-22
    • 1970-01-01
    • 1970-01-01
    • 2017-11-24
    相关资源
    最近更新 更多