Search code examples
reactjstypescriptjestjssegment-analytics

Is there a simple way to mock segment's AnalyticsJS analytics.track() in jest with TypeScript?


In our React/TypeScript app we are tracking analytics with segment.com we use jest for our unit tests.

The segment.com snippet in our index.html adds an analytics object that we can use anywhere in our code and the types are provided.

In one of our tests the code executed calls analytics.track("navigate") and crashes because analytics isn't defined.

I looked into options of mocking the module or assigning an object that has stub implementations. Assigning an object was ugly because I needed to assign mocks to the other 19 methods as well. The module isn't needed by the tests or the real code and importing it so that jest could mock it proved painful.

What is the easiest way to mock just the analytics.track() method for the test?


Solution

  • It turns out there is a simple one line solution. Adding global.analytics = {track: jst.fn() } as any; Casting to any bypasses the type checking and lets us provide a stub implementation so for just the track method so the test can execute cleanly.