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
?
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.
Jest supports TypeScript, via Babel. First, make sure you followed the instructions on using Babel above. Next, install the @babel/preset-typescript : npm.
In setupRoutes.ts
(global as any).Routes = {
some_path: () => {}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With