44

I have function that gets 3 arguments. I want to check that this function not throwing an error. I did something like this:

expect(myFunc).not.toThrow();

The problem is myFunc need to get arguments. How can I send the arguments?

P.S I tried to pass it argument but I got error that myFunc(arg1, arg2, arg3) is not a function.

Sagie
  • 996
  • 3
  • 12
  • 25

3 Answers3

64

toThrow matcher requires function to be passed as argument to expect so you can simply wrap your function call in anonymous function:

expect(function() {
    myFunc(arg1, arg2, arg3);
}).not.toThrow();

You can also use bind to create new 'version' of your function that when called will be passed provided arguments:

expect(myFunc.bind(null, arg1, arg2, arg3)).not.toThrow();
Bartek Fryzowicz
  • 6,464
  • 18
  • 27
1

You can use the .not method:

expect(() => actionToCheck).not.toThrow()

https://jestjs.io/docs/expect#not

arielhad
  • 1,753
  • 15
  • 12
0

If your function throws an exception the test will fail anyways. So it's not necessary to explicitly have an expect statement for it. The problem is that if you don't have an expect statement in your test, it will give you a warning that you have no expectations. The solution is to have an empty expect statement.

myFunc();
expect().nothing();

This is just an alternative way to do it. This can also be useful if you want to make sure that myFunc() finishes at all or just hangs up.

Ádám Bozzay
  • 529
  • 7
  • 19