如何使用Jasmine 2.0测试ES6承诺?

时间:2014-08-16 17:25:58

标签: javascript jasmine promise es6-promise

我有一个返回(probably shimmed) ES6承诺的函数,我想编写一个Jasmine测试,检查它是否成功解析,解析后的值是否正确。我该怎么做?

这是我目前发现的方式,但至少很无聊:

describe("Promises", function() {
  it("should be tested", function(done) {
    var promise = functionThatReturnsAPromise();
    promise.then(function(result) {
      expect(result).toEqual("Hello World");
      done();
    }, function() {
      expect("promise").toBe("successfully resolved");
      done();
    });
  });
});

还有一个名为jasmine-as-promised的库似乎很有用,但遗憾的是它在Jasmine 2.0中不起作用,因为它使用了runs()已被删除。

是否已经开发出适合在Jasmine 2.0中测试承诺的舒适解决方案?

2 个答案:

答案 0 :(得分:3)

这里的派对来不及,但万一其他人发现了这个问题(就像我一样) - 这是一个新答案:使用我的'jasmine-es6-promise-matchers'组件。使用它,上面的测试将如下所示:

var promise = functionThatReturnsAPromise();
expect(promise).toBeResolvedWith("Hello World");

它可以在Bower和NPM上使用(仅install jasmine-es6-promise-matchers)。

答案 1 :(得分:2)

诚实?我使用摩卡。在Mocha中,您可以简单地返回一个promise并且语法非常相似,因为您已经使用Mocha的语法进行异步测试。它看起来像是:

describe("Promises", function() {
  it("should be tested", function() {
    var promise = functionThatReturnsAPromise();
    return promise.then(function(result) {
      expect(result).toEqual("Hello World");
    }, function() {
      expect("promise").toBe("successfully resolved");
    });
  });
});

但是,如果你坚持使用本机承诺并且你不能使用摩卡 - 你拥有的东西可能是唯一的替代品,你可以将模式提取到一个方法中:

function itP(description, itfn){
    it(description, function(done){
        var result = itfn(); // call the inner it
        if(result.then) { // if promise was returned
            result.then(done, function(e){
                throw new Error("Async rejection failed " + e.message); 
            }); // resolve means done, reject is a throw
        } else {
            done(); // synchronous
        }
    }); 
}

itP("something", function(){
   return Promise.reject(); // this turns into a failed test
});
相关问题