4

I am trying to run test case for testing entry point of my web service jest I am facing one issue while running the unit test. Cannot spy the async function, because it is a property not a function.

I am trying to test if the run function is called in the server.js file

The entry file is somewhat like below.


    import config from 'config';

    export default async function run() {
      try {
       /*
         some code
       */
      } catch (err) {
        process.exit(1);
      }
    }

    run();

And the test file is like below


    import run from '../server';
    describe('server-test', () => {
    it('run', async () => {
        const start = require('../server');
        const spy = jest.spyOn(start, run);
        await run();
        expect(spy).toBeCalled();
      });
    });

The test should run properly, but I am getting below error on running this test

Cannot spy the async function run() {

    try {
            /*
             some code.
            */
          } catch (err) {
            process.exit(1);
          }
        } property because it is not a function; undefined given instead
skyboyer
  • 22,209
  • 7
  • 57
  • 64
a_uttav
  • 41
  • 5

1 Answers1

0

I researched for quite a long for this error and ended on the following post How to spy on a default exported function with Jest?

So, without ditching the default keyword (i.e required for ES 6 lint), the only solution is to use 'default' word in place of 'run'.

Use somewhat like this.

const spy = jest.spyOn(start, 'default');

It should work.

a_uttav
  • 41
  • 5