Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest.js - test that specific function is called by the module

The sole purpose of index.js is to run foo and bar functions:

//index.js
import foo from './foo.js'
import bar from './bar.js'

foo()
bar()

How can I test that when running index.js both foo and bar get executed?

like image 623
avalanche1 Avatar asked Nov 28 '25 16:11

avalanche1


1 Answers

Firstly I would concentrate on testing foo and bar functions making sure they do what they have to do.

For example if the function foo is ()=>{ return 'foo() is working' } I make a file called foo.test.js and i write 2-3 tests for it.

test('make sure it returns something', () => {
  expect(!foo()).toBe(false);
});
test('make sure it returns string', () => {
  var val = foo();
  expect(typeof val === 'string').toBe(true);
});
test('make sure it returns string', () => {
  expect(foo()==='foo() is working').toBe(true);
});

This will make sure my foo.js is doing what it suppose to then I make another file called index.text.js and in it I'll do my mock test

jest.mock("../foo");
const foo = require("../foo");

test('make sure foo is called', () => {
  expect(foo).toBeCalled();
});
test('make sure foo run only once', () => {
   expect(foo.mock.calls.length).toBe(1);
});

Now assuming you have installed jest and have package.json configured correctly you can simply run : npm run test or if you have yarn you can just run yarn test...

like image 80
Ash Avatar answered Dec 01 '25 07:12

Ash



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!