简体   繁体   English

尝试和未能通过茉莉花测试诺言

[英]Trying and failing to test promises with Jasmine

(all this example code is coffeescript) (所有示例代码都是coffeescript)

I have a generic promise like so: 我有这样一个通用的承诺:

describe "foo", () ->
  it "foo", () ->

    p = new Promise (r) -> r(1)
    p.then (x) ->
      console.log("promise run")
      expect(x).toEqual(2)

This is expected to fail, but it doesn't. 预计这将失败,但不会失败。 The expectation is never hit and nothing is logged either. 期望永远不会实现,也不会记录任何内容。

From the jasmine team's blog post on the topic it seems I can write something like this: 茉莉花团队关于该主题的博客文章看来,我可以写这样的东西:

p.then (x) ->
  expect(x).toEqual(2)
  done()

but it has the same effect. 但效果一样

The blog post recommends the mock-promises library, which I used to write this: 博客文章推荐了模拟承诺库,我曾经用它来编写:

p.then (x) ->
  console.log x
  expect(x).toEqual(2)
MockPromises.executeForPromise(p);

but it has the same effect (the expectation is never hit) 但它具有相同的效果(永远不会达到期望)

Instant gratification: 及时行乐:

it's an easy fix: 这是一个简单的解决方法:

all I needed to do was pass done as an argument to the it function: 我要做的就是将done作为参数传递给it函数:

describe "foo", () ->
  it "foo", (done) ->
    p = new Promise (r) -> r(1)
    p.then (x) ->
      console.log x
      expect(x).toEqual(2)
      done()

Thanks to a suggestion in the comments I should also add 由于评论中的建议,我还应该添加

.catch(done)

at the end so that failed cases don't just time out. 最后,这样失败的案例就不会超时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM