Ask questionsProvide testing/mocking instructions and export react-tracking/mock

I've been meaning to provide this as importable within react-tracking via something like: import track, { mockTrackEvent, TrackingPropType } from 'react-tracking/mock'; but haven't had a chance yet. PRs welcome! 😁

/* __mocks__/react-tracking.js */

const PropTypes = require('prop-types');

const mockTrackEvent = jest.fn();

module.exports.TrackingPropType = PropTypes.shape();

module.exports = () => (...clsOrMethod) => {
  if (clsOrMethod.length === 1) {
    // decorating a class
    const [cls] = clsOrMethod;
    cls.defaultProps = {
      tracking: {
        trackEvent: mockTrackEvent,
    return cls;

  // decorating a method
  return clsOrMethod[1].initializer;

module.exports.mockTrackEvent = mockTrackEvent;

Originally posted by @tizmagik in


Answer questions wokkaflokka

@tizmagik cc @l225li

With respect to the comment from @l225li, I also observed this issue recently when integrating react-tracking. In my case, our project is a typescript project using stateless functional components and ES module imports, and using jest for testing.

For tracking implemented at the component level, a lot of the code looks like this...

import track from 'react-tracking'

const MyComponent = () => { ... }

export default track({
  event: 'my-component.presented'

The key for mocking, then, is to mock the default exported function (track).

By default, jest mocks do not support ES module semantics; when react-tracking was not mocked for ES module syntax, I observed variants of the error described by @l225li.

 FAIL  src/components/pages/Foo/Bar/Baz/__tests__/Baz.test.tsx
  ● Test suite failed to run

    TypeError: (0 , _reactTracking.default)(...) is not a function

      120 | }
      121 | 
    > 122 | export default track({
          |                ^
      123 |   event: 'foo-bar.baz.presented',
      124 | })(Baz)
      125 | 

      at Object.<anonymous> (src/components/pages/Foo/Bar/Baz/Baz.tsx:123:12)
      at Object.<anonymous> (src/components/pages/Foo/Bar/Baz/__tests__/Baz.test.tsx:10:1)

This prevented me from mocking react-tracking using a manual mock; however, I was able to get a satisfactory mocking solution using the following configuration.

jest.mock('react-tracking', () => {
    const trackEvent = jest.fn()
    return {
        __esModule: true,
        default: jest.fn(() => (id) => id),
        useTracking: jest.fn(() => ({

Hope this helps.

Aside: really love the work NYT team has done with this library. In recent years I have spent a lot of time working on Android (where NYT team also shines), and was very pleasantly surprised to find this library, which shares a core philosophy and solves foundational problems I encountered in past projects in the mobile space. Great job.


Related questions

No questions were found.
Github User Rank List