栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

node.js如何使用Mocha为异步测试获取更好的错误消息

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

node.js如何使用Mocha为异步测试获取更好的错误消息

当您收到超时错误而不是更精确的错误时, 要做的第一件事是检查您的代码没有吞噬异常,也没有吞噬承诺拒绝。
Mocha旨在检测您的测试中的这些。除非您执行不寻常的操作(例如在自己的VM中运行测试代码或操纵域),否则Mocha会检测到此类故障,但是如果您的代码吞噬了这些故障,Mocha将无法执行任何操作。

话虽这么说,Mocha无法告诉您

done
未调用,因为您的实现存在逻辑错误,导致无法调用回调。

sinon
测试失败后执行后期验验可以采取以下措施。让我强调,这是 概念证明 。如果我想持续使用它,那么我将开发一个适当的库。

var sinon = require("sinon");var assert = require("assert");// MyEmitter is just some pre to test, created for the purpose of// illustration.var MyEmitter = require("./MyEmitter");var emitter = new MyEmitter();var postMortem;beforeEach(function () {  postMortem = {    calledOnce: []  };});afterEach(function () {  // We perform the post mortem only if the test failed to run properly.  if (this.currentTest.state === "failed") {    postMortem.calledOnce.forEach(function (fn) {      if (!fn.calledOnce) {        // I'm not raising an exception here because it would cause further        // tests to be skipped by Mocha. Raising an exception in a hook is        // interpreted as "the test suite is broken" rather than "a test        // failed".        console.log("was not called once");      }    });  }});it("client should do something", function(done) {  var doneFn = function(args) {    // If you change this to false Mocha will give you a useful error.  This is    // *not* due to the use of sinon. It is wholly due to the fact that    // `MyEmitter` does not swallow exceptions.    assert(true);    done();  };  // We create and register our spy so that we can conduct a post mortem if the  // test fails.  var spy = sinon.spy(doneFn);  postMortem.calledOnce.push(spy);  emitter.on("foo", spy);  emitter.triggerEvent("foo");});

这是以下代码

MyEmitter.js

var EventEmitter = require("events");function MyEmitter() {    EventEmitter.call(this);}MyEmitter.prototype = Object.create(EventEmitter.prototype);MyEmitter.prototype.constructor = MyEmitter;MyEmitter.prototype.triggerEvent = function (event) {    setTimeout(this.emit.bind(this, event), 1000);};module.exports = MyEmitter;


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/448846.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号