1

I'm trying to Jest test a method of a Vue component that contains FileReader. I need to read a json file.

Method:

    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));
    }

Called by this input file:

<input v-if="!saved" type="file" @change="readConfig" accept=".json">

I tried to follow some solutions, but I can't get the upload to load my json Thanks in advance

Xeyos
  • 61
  • 3
  • Related: https://stackoverflow.com/questions/61572070/how-to-test-filereader-onload-using-simulate-change-in-jest – Estus Flask Sep 15 '21 at 11:42
  • Just tested. I have this error simulate(...) is not a function – Xeyos Sep 15 '21 at 12:11
  • The answer is for React and Enzyme. You need to adjust parts that are specific to Vue test utils accordingly. The part that involves Filereader is the same. – Estus Flask Sep 15 '21 at 12:43
  • Now I am able to enter the fr.onload but JSON.parse always returns " Unexpected token o in JSON at position 1". this call is correct? reader.onload ({target: {result: {"connection": {"type": "rest", "url": "http: // localhost: 3000", "api": "/", "time": 3}}}, files: [{name: 'config.json', size: '20000', type: 'text / json'}]}); – Xeyos Sep 15 '21 at 12:57
  • The error means that an object was provided where JSON string was expected, https://stackoverflow.com/questions/43612837/error-when-unit-testing-uncaught-in-promise-syntaxerror-unexpected-token-o . `result` is supposed to be a string. – Estus Flask Sep 15 '21 at 16:16

1 Answers1

1

Thx for the help. I found the solution to my problem

    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'}] });

    });
Xeyos
  • 61
  • 3