用Jest和Typescript模拟一个全局对象

问题描述 投票:3回答:1

我有一个React组件。无论好坏,我使用Routes公开的js-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放松关于Routes

javascript reactjs typescript jest
1个回答
4
投票

在setupRoutes.ts中

(global as any).Routes = {
  some_path: () => {}
};
© www.soinside.com 2019 - 2024. All rights reserved.