Chai-as-promised: several pending statements in one test

I use chai-as-promised to test some promises. My problem: I'm not sure how to have multiple pending statements in one test. For proper operation, expect().to.be.fulfilledI need to return it, for example:

it('test', () => {
  return expect(promise).to.be.fulfilled
}

... or use notifyfor example:

it('test', (done) => {
  expect(promise).to.be.fulfilled.notify(done)
}

The problem occurs when I have one more thing that I need to check, for example, that a certain function is called, for example:

it('test', (done) => {
  var promise = doSomething()
  expect(sinon_function_spy.callCount).to.equal(1)
  expect(promise).to.be.fulfilled.notify(done)
})

The problem is that since it doSomething()is asynchronous, the call sinon_function_spymay not happen when I call it expect, making this test flaky. If I use then, for example:

it('test', (done) => {
  var promise = doSomething()
  promise.then(() => {
    expect(sinon_function_spy.callCount).to.equal(1)
  })
  expect(promise).to.be.fulfilled.notify(done)
})

, , , - then. , , , :

it('test', (done) => {
  var promise = doSomething()
  promise.then(() => {
    expect(sinon_function_spy.callCount).to.equal(1)
  })
  expect(promise).to.be.rejected.notify(done)
})

sinon_function_spy , then.

expect ?

+4
2

, , , , . - , Promise , :

it('test', () => {
  return doSomething()
    .then(() => {
      expect(sinon_function_spy.callCount).to.equal(1)
    });
});

, doSomething(), , . expect , . :

it('test', () => {
  return doSomething()
    .then(() => {
      expect(sinon_function_spy.callCount).to.equal(1)
    }, err => {
      expect(err).to.not.exist;
    });
});

... . , then , , , Mocha, .

:

it('test', () => {
  return doSomething()
    .then(() => {
      throw new Error('Promise should not have resolved');
    }, err => {
      expect(err).to.exist;
      expect(sinon_function_spy.callCount).to.equal(1)
    });
})
+1

, then():

it('test', () => {
   return doSomething().then( () => {
     expect(sinon_function_spy.callCount).to.equal(1);
   });
});

, , expect . , jasmine-promises .

, :

function reverse( promise ) {
   //use a single then block to avoid issues with both callbacks triggering
   return promise.then(
       () => { throw new Error("Promise should not succeed"); }
       e => e; //resolves the promise with the rejection error
   );
}

it('test', () => {
   return reverse( doSomethingWrong() ).then( error => {
       expect( error.message ).to.equal("Oh no");
   });
});
+2

Source: https://habr.com/ru/post/1690993/


All Articles