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
?
In setupRoutes.ts
(global as any).Routes = {
some_path: () => {}
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.