Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write test for a function which calls another function using jest and enzyme?

I'm using jest and enzyme for testing my app. I've a function as :

const someFunc = (arg1, arg2, arg3) => {
    arg2.someOtherFunc(arg3);
}

Now, I want to write test for function someFunc, I've mocked someOtherFunc and I'll test whether it'll be called with some arg3 but I'm unable to get how I should write the assertion?

My test should assert that after someFunc, it should call someOtherFunc with some arguments.

like image 268
Ajay Gaur Avatar asked Nov 01 '25 04:11

Ajay Gaur


2 Answers

In your case you want to pass the function as a callback And in your tests you have to Mock it and check if it's being called / being called n times or being called with a specific argument.

Check this example below:

// your function
const someFunc = (arg1, arg2, arg3) => {
  arg2.someOtherFunc(arg3);
}

// your test file
it("works", () => {
  const arg1 = 'im just any value doesnt matter';
  const arg2 = {
      someOtherFunc: jest.fn(),
    };
  const arg3 = 'argument';

  someFunc(arg1, arg2, arg3);

  // some assertions you can use
  expect(arg2.someOtherFunc).toBeCalled();
  expect(arg2.someOtherFunc).toBeCalledWith('argument');
  expect(arg2.someOtherFunc).toHaveBeenCalledTimes(1);
});
like image 101
Hichem ben chaabene Avatar answered Nov 03 '25 19:11

Hichem ben chaabene


You can use toHaveBeenCalledWith()

expect(someOtherFunc).toHaveBeenCalledWith('your args');
like image 32
t3__rry Avatar answered Nov 03 '25 19:11

t3__rry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!