javascript - 使用 node.js 的断言引发的测试错误

标签 javascript node.js mocha.js

我对我们应该如何测试错误的文档感到困惑。

我在 index.js 中有这个除法函数

function divide(dividend, divisor) {
    if(divisor === 0) {
      throw new Error('the quotient of a number and 0 is undefined');
    } else {
      return  dividend / divisor;
    }
  }

测试应该是什么样子?我知道这将是 2 种情况,第一种是测试除法,我没有问题,但是如果用户通过零,我不知道如何测试错误。

我正在使用 mocha 和断言( Node 的断言)
describe('.divide', () => {
    it('returns the first number divided by the second number', () => {
      assert.equal(5, Calculate.divide(10,2))
    })

    it('throws an error when the divisor is 0', () => {

    })
})

最佳答案

实现代码如下所示:

  divide(dividend, divisor) {
    if (divisor === 0) {
      throw new Error('the quotient of a number and 0 is undefined');
    } else {
      return dividend / divisor;
    }
  },

测试代码如下所示:
it("returns an exception when the divisor is 0", () => {
  const dividend = 8;
  const divisor = 0;
  expected = Error;

  const exercise = () => Calculate.divide(dividend, divisor);

  assert.throws(exercise, expected);
})

这是根据 nodejs documentation

关于javascript - 使用 node.js 的断言引发的测试错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48841325/

相关文章:

javascript - 如何使用 Dropzone.js 和 Rails 4 重定向提交页面?

node.js - Mongoose 在 Node 中的 "model.findById"之后做一些事情

node.js - TLS + NodeJS,如何在服务器端获取客户端的公钥字节

javascript - 我如何找到文档数组中等于或大于值的所有值

node.js - mocha/chai 和 ES6 Promise 的奇怪断言失败

node.js - "before all"钩子(Hook)随机出现在我的测试中

post - Mocha 测试(POST 请求): error outside of test suite

javascript - 空注入(inject)器错误 : No provider for MatBottomSheetRef

javascript - Imgur API 图像搜索不返回数据

javascript - 拖放和 Bootstrap UI Accordion