Skip to content

Instantly share code, notes, and snippets.

@greenlikeorange
Last active August 22, 2016 13:22
Show Gist options
  • Save greenlikeorange/a18d3a969becff62fbb99b4dc381d87e to your computer and use it in GitHub Desktop.
Save greenlikeorange/a18d3a969becff62fbb99b4dc381d87e to your computer and use it in GitHub Desktop.
Add ".also" Langauge chain to chai.expect to make test with multi scenarios Promise test case;
'use strict';
const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');
const expectChain = require('./expectChain');
chai.use(chaiAsPromised);
chai.use(expectChain);
const expect = chai.expect;
describe('Expect Chain test', () => {
const p = () => Promise.resolve({id: 1000, devices: [{id: 1, date: Date.now()}], time: Date.now()})
it('should success', () => {
let now = Date.now();
return expect(p())
.also.eventually.have.deep.property("id", 1000)
.also.eventually.have.deep.property("devices")
.also.eventually.have.deep.property("time")
.that.be.at.least(now)
.exec(); // Must call .exec to execute all promises in chain
});
});
module.exports = (chai) => {
// Original
const _expect = chai.expect;
// Create .also able expect
chai.expect = (obj) => {
// This will not work for non Promise Object
if (!obj.toString().match('[object Promise]'))
return _expect(obj);
let chains = [ _expect(obj) ];
function addAlso(chain) {
Object.defineProperty(chain, "also", { get: () => {
chains.push(_expect(obj)); // Add to Chains
return addAlso(chains[chains.length - 1]).to;
}});
chain.exec = () => Promise.all(chains);
return chain;
}
return addAlso(chains[0]);
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment