使用断言 node.js 抛出的测试错误

test error thrown using assert of node.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;
    }
  }

测试应该是什么样子的?我知道会有两种情况,第一种是测试除法,我没问题,但我不知道如果用户传递零时如何测试错误。

我正在使用 mocha 和断言(节点的断言)

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