ѺȐeallү
ѺȐeallү

Reputation: 3017

How do you unit test Javascript Promises using Jasmine.js?

What is a common, correct, or accepted way to Unit test functions using Javascript Promises properly using Jasmine?

Example Promise:

function readFile(filename, enc) {
  return new Promise(function (fulfill, reject) {
    fs.readFile(filename, enc, function (err, res) {
      if (err) reject(err);
      else fulfill(res);
    });
  });
}

function readJSON(filename) {
  return new Promise(function (fulfill, reject) {
    readFile(filename, 'utf8').done(function (res) {
      try {
        fulfill(JSON.parse(res));
      } catch (ex) {
        reject(ex);
      }
    }, reject);
  });
}

The solution should contain a test for the sample code above. Thanks!

Upvotes: 1

Views: 464

Answers (1)

Kris Kowal
Kris Kowal

Reputation: 3846

You might consider using Jasminum. I’ve designed it for promises, using Q promises but it can use any conforming Promise constructor.

describe("readFile", function () {
    it("reads a file", function () {
        return readFile(__filename)
        .then(function (content) {
            expect(content).toContain("Unlikely nonce: Xebrohio!");
        });
    });
});

Upvotes: 1

Related Questions