Is there a way to get Chai working with asynchronous Mocha tests?

后端 未结 13 2170
自闭症患者
自闭症患者 2020-11-29 21:06

I\'m running some asynchronous tests in Mocha using the Browser Runner and I\'m trying to use Chai\'s expect style assertions:

window.expect = chai.expect;
d         


        
13条回答
  •  北海茫月
    2020-11-29 21:19

    Very much related to and inspired by Jean Vincent's answer, we employ a helper function similar to his check function, but we call it eventually instead (this helps it match up with the naming conventions of chai-as-promised). It returns a function that takes any number of arguments and passes them to the original callback. This helps eliminate an extra nested function block in your tests and allows you to handle any type of async callback. Here it is written in ES2015:

    function eventually(done, fn) {
      return (...args) => {
        try {
          fn(...args);
          done();
        } catch (err) {
          done(err);
        }
      };
    };
    

    Example Usage:

    describe("my async test", function() {
      it("should fail", function(done) {
        setTimeout(eventually(done, (param1, param2) => {
          assert.equal(param1, "foo");   // this should pass
          assert.equal(param2, "bogus"); // this should fail
        }), 100, "foo", "bar");
      });
    });
    

提交回复
热议问题