0

I have a React Functional Component, and I want to write a unit test that checks if a function that gets called further down the chain has actually been called as a result of the component getting rendered.

I don't care which library I use, or which exact method from said library I use - I just want to be able to test that otherHelper has been called, so feel free to suggest other approaches than this one below.

helper.ts

export const otherHelper = () => {}

export const helper = () => {
  otherHelper()
}

App.tsx

import { helper } from './helper'

const App = () => {
  helper()

  return <h1>App</h1>
}

Now, here is what I'd like my test to be:

App.test.tsx

import { App } from './App'
import {otherHelper} from './helper'
import {render} from '@testing-library/react'

describe("App", () => {
  it("calls otherHelper", () => {
    const RenderedApp = render(<App />)
    const spy = jest.spyOn(RenderedApp, otherHelper)
    expect(spy).toHaveBeenCalled()    
  })
})

Currently this does not work. Any ideas on how to make it work?

Because Jest's spyOn method requires an object, I'd be happy to re-write my otherHelper code as follows:

helper.ts

export const otherHelper = { 
  help: () => {} 
}
Ben
  • 5,085
  • 9
  • 39
  • 58

1 Answers1

0

You can mock the entire helper module, see jest docs for mocking modules.

In your case it might be something like:

const mockedHelper = jest.fn(() => true);
jest.mock('./helper', () => {
  const originalModule = jest.requireActual('./helper');
  return {
    helper: mockedHelper,
    ...originalModule
  };
});

...

expect(mockedHelper).toHaveBeenCalled();
szaman
  • 2,159
  • 1
  • 14
  • 30
  • Thanks. Your expect statement just checks if the entire module has been called. How do you check if `otherHelper` has been called? – Ben Nov 12 '21 at 11:54
  • instead of returning `helper: mockedHelper` in the mock, try `otherHelper: mockedHelper,`. – szaman Nov 12 '21 at 11:56
  • you might need to change your import in the App component from `import { helper } from './helper'` to `import { otherHelper } from './helper'` – szaman Nov 12 '21 at 11:57
  • When I do `jest.mock('./helper')`, then I can test it with `.toHaveBeenCalled()`, but when I do it with the factory as above in your example, then it does not work. Same goes for `otherHelper`. – Ben Nov 12 '21 at 13:46
  • This solution did not work. :( – Ben Nov 12 '21 at 15:00