在我的应用程序中,我在外部文件中有一个全局变量
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');
});
我收到错误&#34; TypeError:Translator.trans不是函数&#34;
Jest设置
"jest": {
"verbose": true,
"rootDir": "./src",
"globals": {
"Translator": true
}
}
如何更好地模拟全局变量?谢谢!
答案 0 :(得分:0)
这是解决方案,无需设置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
答案 1 :(得分:0)
这是为Jest全局模拟变量/函数的一种方法:
"en": 26.32
"de": 23.51
...
mockTranslate.js
然后在您的// Globally mock gettext
global.gettext = jest.fn((text) => text);
global.pgettext = jest.fn((context, text) => text);
中将其包括在jest.config.js
中:
setupFiles