期望失败时如何拦截错误? 茉莉花和弗里斯比

我正在用jasmine.js工作的frisby.js创buildHTTPtesting。

我也必须创build一些mongoDB对象来testing。 问题是当我想清理这些数据库对象。 当其中一个期望失败时,我想拦截并调用我自己的清理函数。 这意味着在每次失败的testing之后,我将无法从DB中删除testing对象。

在茉莉花afterEachfunction不能正常工作,茉莉花没有任何支持afterAll或beforeAll呢。 这就是为什么我今天做了testing。

it("testing userform get with correct userID and expect correct return", function() { var innerUserId = userID; frisby.create('Should retrieve correct userform and return 200 when using a valid userID') .get(url.urlify('/api/userform', {id: innerUserId})) .expectStatus(200) .afterJSON(function(userform){ // If any of these fail, the after function wont run. // I want to intercept the error so that I can make sure that the cleanUp function is called // afterEach does not work. I have tried with done() var useridJSON = userform.UserId.valueOf(); var firstnameJSON = userform.firstname.valueOf(); var surnameJSON = userform.surname.valueOf(); expect(firstnameJSON).toMatch(testUser.firstName); expect(surnameJSON).toMatch(testUser.surname); expect(useridJSON).toMatch(innerUserId); }) .after(function(){ cleanUp(innerUserId); }) .toss(); }); 

我想知道是否有方法来拦截frisby或jasmine中的“expect”错误,这样我可以在退出之前调用我自己的清理函数。

完整的例子

解决这个问题的最快捷的方法是将错误代码封装在try-catch中。 这是因为如果发生javascript错误,茉莉花不会保持运行断言。 这与断言错误不同。 如果发生断言错误,茉莉花和frisby将继续testing所有其他断言,然后执行“after”function。

  .afterJSON(function(userform){ try { var useridJSON = userform.UserId.valueOf(); var firstnameJSON = userform.firstname.valueOf(); var surnameJSON = userform.surname.valueOf(); catch(e) { cleanUp(innerUserId); // Can do a throw(e.message); here aswell } expect(firstnameJSON).toMatch(testUser.firstName); expect(surnameJSON).toMatch(testUser.surname); expect(useridJSON).toMatch(innerUserId); }) 

这不是美丽的方式,但工作。

我最后添加了throw(e),并把期望放在了最后的范围内。 通过这种方式,我得到了茉莉花来呈现在testing中发生的所有错误。

至于“退出前”,这个怎么样:

 process.on('uncaughtException', function(err) { console.error(' Caught exception: ' + err); });