Jasmine可以用来测试并发失败吗?

Can Jasmine be made to test for concurrency failures?

本文关键字:并发 失败 测试 Jasmine      更新时间:2023-09-26

我怀疑基于其他响应(如Jasmine:测试setTimeout函数抛出错误和如何测试具有Jasmine setTimeout的函数?),这里没有好的解决方案,但我想弄清楚如何更好地处理下面的第二个测试:

describe('Tests', function () {
    it('succeed', function () { expect(true).toBeTruthy(); });
    it('have problems', function(done) {
        setTimeout(function() { console.log(undefined.foo); });
        setTimeout(done, 5);
    });
    it('fail', function() { fail; });
    it('also fail', function() { fail; });
});

Jasmine当前的行为是运行第一个测试,然后在第二个测试中遇到导致异常的setTimeout时退出;最后两个失败的规范永远不会运行。

当然,我的用例不是这样的!异步错误发生在调用堆栈的某个地方,越过河流,穿过树林。这显然是一个错误,它发生了,没有被捕获!但是不幸的是,如果这样的错误总是终止Jasmine本身,而不是导致测试用例失败。

我相信你想要try...catch或承诺与Jasmine的done.fail()

承诺:

it('gets some huge file', done => {
  getFile('http://movies.com/holymountain.mp4')
    .then(res => {
      expect(res.status).toBe(200)
      done()
    })
    .catch(done.fail)
})

Try/catch

it('gets some huge file', done => {
  try {
    getFile('http://movies.com/holymountain.mp4')
    expect(getFile.status).toBe(200)
    done()
  } catch (e) {
    // console.log(e) // ???
    done.fail()
  }
})

参考问题