簡體   English   中英

如何用Jasmine 2.0測試ES6 Promise?

[英]How to test ES6 promises with Jasmine 2.0?

我有一個函數返回( 可能是勻場的) 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-promise的庫,它似乎很有幫助,但可惜的是它在Jasmine 2.0中不起作用,因為它使用了已被刪除的runs()

是否已經開發出舒適的解決方案來測試Jasmine 2.0中的承諾?

在這里參加聚會的時間不算太晚,但是萬一其他人發現了這個問題(我也一樣)-這是一個新答案:使用我的“ jasmine-es6-promise-matchers ”組件。 使用它,您上面的測試將如下所示:

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

在Bower和NPM上可用(只需install jasmine-es6-promise-matchers )。

老實說 我會用摩卡咖啡。 在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");
    });
  });
});

但是,如果您堅持使用原生的Promise,並且不能使用mocha-可能的確是唯一的選擇,則可以將模式提取到方法中:

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
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM