Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock a global object with Jest and Typescript

I have a React component. For good or bad, I use the Routes global object exposed by js-routes - a gem for Rails. I have a snapshot test using Jest which tests my simple component that happens to use the Routes global.

In my test I want to mock Routes. So when my component calls Routes.some_path(), I can just return some arbitrary string.

The error that I mainly get is Cannot find name 'Routes'..

Here is my setup:

package.json

"jest": {
  "globals": {
    "ts-jest": {
      "enableTsDiagnostics": true
    }
  },
  "testEnvironment": "jsdom",
  "setupFiles": [
    "<rootDir>/app/javascript/__tests__/setupRoutes.ts"
  ]
...

setupRoutes.ts (This seemed like the most popular solution)

const globalAny:any = global;

globalAny.Routes = {
  some_path: () => {},
};

myTest.snapshot.tsx

import * as React from 'react';
import {shallow} from 'enzyme';
import toJson from 'enzyme-to-json';

import MyComponent from 'MyComponent';

describe('My Component', () => {
  let component;

  beforeEach(() => {
    component = shallow(<MyComponent />);
  });

  it('should render correctly', () => {
    expect(toJson(component)).toMatchSnapshot();
  });
});

MyComponent.tsx

import * as React from 'react';
import * as DOM from 'react-dom';

class MyComponent extends React.Component<{}, {}> {

  render() {
    return <div>{Routes.some_path()}</div>;
  }
}

export default MyComponent;

If I console.log(window) in the test, Routes does exist. So I'm not sure why it doesn't like Routes being used int he component. In fact it must be Typescript thinking it doesn't exist but at run time it does. I guess my question then is how can I tell Typescript to chill out about Routes?

like image 526
preeve Avatar asked Feb 28 '18 10:02

preeve


People also ask

How do you mock globals in Jest?

When mocking global object methods in Jest, the optimal way to do so is using the jest. spyOn() method. It takes the object and name of the method you want to mock, and returns a mock function. The resulting mock function can then be chained to a mocked implementation or a mocked return value.

Can you use Jest with TypeScript?

Jest supports TypeScript, via Babel. First, make sure you followed the instructions on using Babel above. Next, install the @babel/preset-typescript : npm.


1 Answers

In setupRoutes.ts

(global as any).Routes = {
  some_path: () => {}
};
like image 57
paibamboo Avatar answered Oct 05 '22 04:10

paibamboo