QUnit test not working on assert.throws()

43 views Asked by At

Maybe i don't understand the documentation, my test is not working.

I'll test an expected error from a function:

// file_to_test.js
...
myFunctionToTest: function(param1, param2 = "AA-BB") {
  const idx1 = param2.indexOf("AA");
  if(idx1 === -1) {
    throw new Error('test message error');
  }
}

here comes the test:

// test.js
sap.ui.define(["path/to/my/script"], function(myScriptToTest) {
  ...
  QUnit.test('should thrown error', assert => {
    assert.throws(
      function() {
        myScriptToTest.myFunctionToTest('blabla', 'blubblub'); // test is broken at this line
      },
      function(error) {
        return error.toString() === 'test message error';
      },
      'Error thrown'
    }
  })
})

The return (Browser-)output:

1. Error thrown
Expected:   function( a ){
  [code]
}
  Result: Error("test message error")
  Diff: function( a ){
          [code]
        }Error("test message error")
Source: ...

How to setup the test correctly?

1

There are 1 answers

0
Timo Tijhof On

Your QUnit code looks fine, but there is a mistake in how you've written your JavaScript logic.

It is actually true that error.toString() does not equal test message error. What you're looking for is error.message and not error.toString().

Consider the following:

var myerror = new Error('hello world');
console.log(myerror.toString());
// 'Error: hello world'
console.log(myerror.toString() === 'hello world');
// false

console.log('-------');

console.log(myerror.message);
// 'hello world'
console.log(myerror.message === 'hello world');
// true

See also: