admin管理员组

文章数量:1291026

I'm confused looking at the documention how we should test the error.

I have this divide function in 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;
    }
  }

How should the test look like? I know it gonna be 2 case, the first one is to test the divide, I have no problem with it, but I have no clue how to test the error if user pass zero.

I'm using mocha and assert (node's assert)

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', () => {

    })
})

I'm confused looking at the documention how we should test the error.

I have this divide function in 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;
    }
  }

How should the test look like? I know it gonna be 2 case, the first one is to test the divide, I have no problem with it, but I have no clue how to test the error if user pass zero.

I'm using mocha and assert (node's assert)

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', () => {

    })
})
Share Improve this question asked Feb 17, 2018 at 12:34 Chuang yeChuang ye 651 gold badge1 silver badge3 bronze badges 1
  • 1 assert.throws or try/catch with assert true/false (true in catch block). – Egor Stambakio Commented Feb 17, 2018 at 12:37
Add a ment  | 

1 Answer 1

Reset to default 7

The implementation code would look like this:

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

The test code would look like this:

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);
})

This is according to the nodejs documentation

本文标签: javascripttest error thrown using assert of nodejsStack Overflow