【问题标题】:Mock a global object with Jest and Typescript用 Jest 和 Typescript 模拟一个全局对象
【发布时间】: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


    【解决方案1】:

    setupRoutes.ts

    (global as any).Routes = {
      some_path: () => {}
    };
    

    【讨论】:

    • 不起作用,我仍然收到error TS2304: Cannot find name 'Routes'。你能提供一个小的工作示例吗?
    猜你喜欢
    • 2019-11-22
    • 2021-08-26
    • 2018-03-31
    • 2017-03-19
    • 1970-01-01
    • 2016-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多