JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/3.0.2/mocha.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/mocha/3.0.2/mocha.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/chai/3.5.0/chai.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chai/3.5.0/chai.js"></script>
<div id="mocha"></div>
JavaScript
mocha.setup('bdd');
const assert = chai.assert;
describe('Promise の多数決待ち合わせ', () => {
[
{
willBeFulfilled: [false, false, false],
expectToBeFulfilled: false,
},
{
willBeFulfilled: [false, false, true],
expectToBeFulfilled: false,
},
{
willBeFulfilled: [false, true, false],
expectToBeFulfilled: false,
},
{
willBeFulfilled: [false, true, true],
expectToBeFulfilled: true,
},
{
willBeFulfilled: [true, false, false],
expectToBeFulfilled: false,
},
{
willBeFulfilled: [true, false, true],
expectToBeFulfilled: true,
},
{
willBeFulfilled: [true, true, false],
expectToBeFulfilled: true,
},
{
willBeFulfilled: [true, true, true],
expectToBeFulfilled: true,
},
].forEach(({ willBeFulfilled, expectToBeFulfilled }) => {
context(`与えられた Promise がそれぞれ ${formatContext(willBeFulfilled)} のとき`, () => {
it(`結果として ${expectToBeFulfilled ? '解決する' : '解決しない'} Promise を返すべきだ`, () => {
const promises = willBeFulfilled
.map((fulfilled) => fulfilled ? everFulfilled()
: neverFulfilled());
const assertion = expectToBeFulfilled ? assertFulfilled
: assertNeverFulfilled;
return assertion(Promise.race([
Promise.all([promises[0], promises[1]]),
Promise.all([promises[1], promises[2]]),
Promise.all([promises[2], promises[0]]),
]));
});
});
});
});
function formatContext(willBeFulfilled) {
return `[${willBeFulfilled.map((fulfilled) => fulfilled ? '解決' : '未解決').join(', ')}]`;
}
function everFulfilled() {
return Promise.resolve();
}
function neverFulfilled() {
return new Promise(() => {});
}
function timeout(msec) {
return new Promise((resolve) => {
setTimeout(resolve, msec);
});
}
function assertNeverFulfilled(promise) {
return Promise.race([
...