【发布时间】:2018-08-08 04:34:07
【问题描述】:
我有一个 React 组件。无论好坏,我都使用js-routes 公开的Routes 全局对象——Rails 的宝石。我有一个使用 Jest 的快照测试,它测试我碰巧使用 Routes 全局的简单组件。
在我的测试中,我想模拟 Routes。所以当我的组件调用Routes.some_path()时,我可以返回任意字符串。
我主要得到的错误是Cannot find name 'Routes'.。
这是我的设置:
package.json
"jest": {
"globals": {
"ts-jest": {
"enableTsDiagnostics": true
}
},
"testEnvironment": "jsdom",
"setupFiles": [
"<rootDir>/app/javascript/__tests__/setupRoutes.ts"
]
...
setupRoutes.ts(这似乎是最流行的解决方案)
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;
如果我在测试中console.log(window),Routes 确实存在。所以我不确定为什么它不喜欢在组件中使用Routes。事实上,它一定是 Typescript 认为它不存在,但在运行时它确实存在。
我想我的问题是如何告诉 Typescript 冷静一下 Routes?
【问题讨论】:
标签: javascript reactjs typescript jestjs