How can I mock functions used by the component I want to test?

// Here are some functions we want to use for analytics
export default = (data) => window.digitalData.push(data) 
const popData = () => window.digitalData.pop(data) 
export { popData }
// Our component makes use of the calls to the analytic functions
import * from './analytics'
const Header = () => {
  pushData('header loaded')
  popData()
  return <h1>Title</h1>
}
// This is how we can test our component, while mocking the analytics calls it makes.
// If we do NOT mock these analytic calls, our tests may fail with a message stating
// that `window.digitalData` is undefined.
import { shallow } from 'enzyme'
import * as analytics from './analytics'
describe('<Header />', () => {
  const originalDefault = analytics.default
  const originalPopData = analytics.popData
  beforeEach(() => {
    analytics.default = jest.fn()
    analytics.popData = jest.fn()
  })
  afterEach(() => {
    analytics.default = originalDefault
    analytics.popData = originalPopData
  })
  it('should render correctly', () => {
    const header = shallow(<Header />)
    expect(header.text()).toBe('Title')
  })
})

Last updated

Was this helpful?