Jest模拟全局变量的方法

6l7fqoea  于 2022-12-08  发布在  Jest
关注(0)|答案(2)|浏览(250)

在我的应用程序中,外部文件中有一个全局变量

const Translate = {
  trans: () => {... some code}
}

我在我的React组件中使用它

const title = Translate.trans('title');

在我的Component.test.js中

import React from 'react';
import Enzyme, { shallow } from 'enzyme';
import toJson from 'enzyme-to-json';
import Adapter from 'enzyme-adapter-react-16';
import Component from '../Component';
Enzyme.configure({ adapter: new Adapter() });

describe('Component Snapshot Tests', () => {
  it('renders default Component correctly', () => {
    const wrapper = shallow(<Component />);
    expect(toJson(wrapper)).toMatchSnapshot();
  });
});

afterEach(() => {
  global.Translator.trans = jest.fn(() => 'test text');
});

出现错误:
“类型错误:转换器.trans不是函数”
玩笑设置

"jest": {
    "verbose": true,
    "rootDir": "./src",
    "globals": {
      "Translator": true
    }
  }

如何更好地模拟全局变量的笑话?谢谢!

wpcxdonn

wpcxdonn1#

这里是解决方案,没有必要设置jest配置。
index.ts

import React from 'react';
import './Translate';

interface ISomeComponentProps {
  title: string;
}

class SomeComponent extends React.Component<ISomeComponentProps> {
  public render() {
    const title = (global as any).Translator.trans(this.props.title);
    return <div>title: {title}</div>;
  }
}

export { SomeComponent };

Translate.ts

const Translator = {
  trans: text => text
};

(global as any).Translator = Translator;

export { Translator };

单元测试:

import React from 'react';
import { shallow } from 'enzyme';
import { SomeComponent } from './';

(global as any).Translator.trans = jest.fn();

describe('SomeComponent', () => {
  it('t1', () => {
    const mockTitle = 'test title';
    (global as any).Translator.trans.mockReturnValueOnce(mockTitle);
    const wrapper = shallow(<SomeComponent title={mockTitle} />);
    expect(wrapper.text()).toBe(`title: ${mockTitle}`);
    expect((global as any).Translator.trans).toBeCalledWith(mockTitle);
  });
});

包含覆盖率报告的单元测试结果:

PASS  src/stackoverflow/47412169/index.spec.tsx
  SomeComponent
    ✓ t1 (14ms)

--------------|----------|----------|----------|----------|-------------------|
File          |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
--------------|----------|----------|----------|----------|-------------------|
All files     |    92.31 |      100 |    66.67 |    91.67 |                   |
 Translate.ts |       75 |      100 |        0 |       75 |                 2 |
 index.tsx    |      100 |      100 |      100 |      100 |                   |
--------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        3.799s, estimated 6s

以下是完整的演示:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/47412169

nukf8bse

nukf8bse2#

这里有一种方法可以在Jest中全局模拟变量/函数:
mockTranslate.js

// Globally mock gettext
global.gettext = jest.fn((text) => text);
global.pgettext = jest.fn((context, text) => text);

然后在您的jest.config.js中将其包含在setupFiles中:

const config = {
 // other configs
};

// HERE
config.setupFiles = ['./mockTranslate.js'];

module.exports = config;

相关问题