[英]Mock a global object with Jest and Typescript
我有一個React組件。 無論好壞,我使用js-routes
公開的Routes
全局對象 - 一個用於Rails的gem。 我使用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放松Routes
呢?
在setupRoutes.ts中
(global as any).Routes = {
some_path: () => {}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.