Mocking TimelineMax and TweenMax modules in Jest

Viewed 867

I'm trying to mock my import with animations, but I keep getting

● Test suite failed to run

    C:\work\portfolio\node_modules\gsap\TweenMax.js:13
    import TweenLite, { TweenPlugin, Ease, Power0, Power1, Power2, Power3, Power4, Linear } from "./TweenLite.js";
           ^^^^^^^^^

    SyntaxError: Unexpected identifier

The error is from one of the imports from my file.

App.js

const App = () => (
  <ChronologyGraph
    width="700"
    height="800"
    nodeSize={10}
    milestones={milestones.reverse()}
    columns={nodeTypes}
  />
);

export default App;

inside of ChronologyGraph I import my component ProjectNode which imports another file I made animation.js and inside of animation.js I import

import { TimelineMax, Power0 } from "gsap/TweenMax";
import { TweenMax } from "gsap/TweenMaxBase";

Which are causing the error above, I want to either mock this gsap library or just my animation.js

App.test.js

import React from "react";
import { shallow } from 'enzyme';
import App from "./App";

fit("renders without crashing", () => {
  jest.mock('../animation.js');
  jest.mock('gsap/TweenMaxBase');
  jest.mock('gsap/TweenMax');

  const wrapper = shallow(<App />);
});

And here are all the mocks I've tried without any success

3 Answers

Coming late to this, but sharing because the solution is very simple. (I've already answered here as well)

If you read Jest documentation you can simply mock GSAP creating a file in __mocks__ directory.

Mocking TweenMax

Let's say you are importing TweenMax and you want to use to method:

import { TweenMax } from "gsap/TweenMax";

Add two files into the mocks directory. TweenLite can be empty.

.
└── __mocks__
    └── gsap
        └── TweenMax.js
        └── TweenLite.js 
module.exports = {
  TweenMax: class{
    static to(selector, time, options) {
      return jest.fn();
    }
  }
}

You've successfully mock your TweenMax.to method.

Mocking TimelineMax

Because TimelineMax works on instances of a class the mock should be done this way:

import { TimelineMax } from "gsap/TimelineMax";

Again, add two files into the mocks directory. TweenLite can be empty.

.
└── __mocks__
    └── gsap
        └── TweenLite.js 
        └── TimelineMax.js 
module.exports = {
  TimelineMax: class {
    constructor(){
      this.to = jest.fn().mockReturnThis();
    }
  }
};

Use mockReturnThis() to be able to chain methods.

You could try using the UMD version instead, like:

import TweenLite from "gsap/umd/TweenLite"

please update your jest config:

"transform": {
  "\\.js$": "<rootDir>/node_modules/babel-jest"
}

and install babel-jest. Further if your issue wouldn't get resolved then share your jest config and we don't usually mock imports.

Related