Last active
August 22, 2016 13:22
Add ".also" Langauge chain to chai.expect to make test with multi scenarios Promise test case;
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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 | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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