使用Jest和Typescript模拟全局对象

pre*_*eve 4 javascript typescript reactjs jest

我有一个React组件。无论好坏,我都使用由Routes公开的全局对象-Rails js-routes的宝石。我有一个使用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"
  ]
...
Run Code Online (Sandbox Code Playgroud)

setupRoutes.ts(这似乎是最受欢迎的解决方案)

const globalAny:any = global;

globalAny.Routes = {
  some_path: () => {},
};
Run Code Online (Sandbox Code Playgroud)

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();
  });
});
Run Code Online (Sandbox Code Playgroud)

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;
Run Code Online (Sandbox Code Playgroud)

如果我console.log(window)在测试中,Routes确实存在。所以我不确定为什么它不喜欢Routes在组件中使用。实际上,一定是Typescript认为它不存在,但在运行时确实存在。我想我的问题是,如何告诉Typescript放松一下Routes

pai*_*boo 5

setupRoutes.ts中

(global as any).Routes = {
  some_path: () => {}
};
Run Code Online (Sandbox Code Playgroud)