mercredi 23 août 2017

Jasmine.js: Expected function to throw an Error, but it threw Function

I'm trying to get used to writing unit tests in Jasmine (and in general) with a simple calculator application (which you can see at my Github).

One thing I'd like to make sure is that if you pass a string into the calculator, that a TypeError is thrown. To this end, I've written the following code into the function:

Calculator.prototype.addition = function (num1, num2) {
  if (isNaN(num1) || isNaN(num2)) {
    throw TypeError;
  }
  return num1 + num2;
};

and the following code for a test:

var Calculator = require('../../lib/calculator/Calculator');

describe("Calculator", function () {

  let calc = new Calculator();
  var num1 = 2;
  var num2 = 2;

it("should throw a type error if the addition method is given one string", function() {
    expect(function() {calc.addition('lol', num2)}).toThrowError(TypeError);
  });

Attempting to run tests with this code gives the following output:

➜  calculator git:(master) ✗ npm test

> calculator@1.0.0 test /Users/somedude/Workspace/small_projects/calculator
> jasmine

Started
....F*.....

Failures:
1) Calculator should throw a type error if the addition method is given one string
  Message:
    Expected function to throw an Error, but it threw Function.
  Stack:
    Error: Expected function to throw an Error, but it threw Function.
        at UserContext.<anonymous> (/Users/somedude/Workspace/small_projects/calculator/spec/calculator/CalcSpec.js:22:53)
Pending:

1) Calculator should throw a type error if the addition method is given two strings
  Temporarily disabled with xit

11 specs, 1 failure, 1 pending spec
Finished in 0.015 seconds

npm ERR! Test failed.  See above for more details.

This has me confused. The expect statement doesn't work if I don't pass in the function call as an anonymous function, but then it doesn't like this, either.

Aucun commentaire:

Enregistrer un commentaire