Azeem
Azeem

Reputation: 145

Read files in mocha tests asynchronously?

I'm not getting the value of Input and Output variables. I have tried using this keyword also in the below code.

it("Final Decoding Tests", () => {
  let input = "";
  let output = "";

  fs.readFile("./test/test_data/booksEncoded.txt", { encoding: "utf-8" }, (err, data) => {
    if (!err) {
      this.input = data;
    } else {
      console.log(err);
    }
  });

  fs.readFile("./test/test_data/books.xml", { encoding: "utf-8" }, (err, data) => {
    if (!err) {
      this.output = data;
    } else {
      console.log(err);
    }
  });

  console.log(input); // NO OUTPUT
  console.log(this.output); //PRINTS undefined
});

I think I have to read the files asynchronously using the done callback.

My question is:

Why I'm not getting any values for the input and output outside the fs.readFile methods? and Is there any way to read it using done keyword asynchronously?

Upvotes: 1

Views: 854

Answers (1)

Lin Du
Lin Du

Reputation: 102347

You can use util.promisify(original) method to get a promise version of fs.readFile.

E.g.

index.spec.js:

const util = require("util");
const path = require("path");
const fs = require("fs");
const { expect } = require("chai");

const readFile = util.promisify(fs.readFile);

describe("57841192", () => {
  it("Final Decoding Tests", async () => {
    const basepath = path.resolve(__dirname, "./test/test_data");
    const options = { encoding: "utf-8" };
    const readInput = readFile(path.join(basepath, "booksEncoded.txt"), options);
    const readOutput = readFile(path.join(basepath, "books.xml"), options);
    const [input, output] = await Promise.all([readInput, readOutput]);
    expect(input).to.be.equal("haha");
    expect(output).to.be.equal("<item>unit test</item>");
    console.log(input);
    console.log(output);
  });
});

Unit test result:

  57841192
haha
<item>unit test</item>
    ✓ Final Decoding Tests


  1 passing (9ms)

---------------|----------|----------|----------|----------|-------------------|
File           |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
---------------|----------|----------|----------|----------|-------------------|
All files      |      100 |      100 |      100 |      100 |                   |
 index.spec.js |      100 |      100 |      100 |      100 |                   |
---------------|----------|----------|----------|----------|-------------------|

Source code: https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/57841192

Upvotes: 1

Related Questions