Reactjs 如何测试global.i18n.t

Reactjs 如何测试global.i18n.t,reactjs,jestjs,enzyme,Reactjs,Jestjs,Enzyme,Google analytics已添加到ReactJS中的组件以及如何测试,因为它在测试时会给出未定义的错误 render() { return ( <div className='form-wrapper'> <h2 className='register-form-title'>{global.i18n.t('great_offers.title')}</h2> <OTPForm otpChange={this._ot

Google analytics已添加到ReactJS中的组件以及如何测试,因为它在测试时会给出未定义的错误

render() {
return (
  <div className='form-wrapper'>
    <h2 className='register-form-title'>{global.i18n.t('great_offers.title')}</h2>
    <OTPForm
      otpChange={this._otpChange}
      errorMessage={this.state.error}
      handleSubmit={this._handleSubmit}
      valid={this.state.valid}
    />
  </div>
);
  }
render(){
返回(
{global.i18n.t('great_offers.title')}
);
}

在上面的代码中,在进行单元测试时,它说“无法读取未定义的属性t”。那么有没有办法在开始时将其初始化为某个值。而且global.i18n.t在JS中不是有效的变量名,所以我也不能初始化它。

Jest
提供了一个
global
对象,可用于为单元测试设置全局变量。以下是一个例子:

此组件:

import * as React from 'react';

export default ()=> {
  return (
    <div>
      <h2>{global.i18n.t('string_id')}</h2>
    </div>
  );
}
import*as React from'React';
导出默认值()=>{
返回(
{global.i18n.t('string_id')}
);
}
…可以这样进行测试:

import * as React from 'react';
import { shallow } from 'enzyme';

import Component from './component';

// create global i18n object containing a spy as t()
global.i18n = {
  t: jest.fn((key) => 'global.18n.t() called with ' + key)
}

describe('Component', () => {

  it('should render and call global.i18n.t()', () => {
    expect(shallow(<Component />)).toMatchSnapshot();
    expect(global.i18n.t).toHaveBeenCalledTimes(1);
    expect(global.i18n.t).toHaveBeenCalledWith('string_id');
  });

});
import*as React from'React';
从“酶”导入{shall};
从“./Component”导入组件;
//创建包含间谍的全局i18n对象作为t()
global.i18n={
t:jest.fn((key)=>global.18n.t(),用“+key”调用)
}
描述('组件',()=>{
它('应该呈现并调用global.i18n.t()',()=>{
expect(shall()).toMatchSnapshot();
预计(global.i18n.t.)已被催收时间(1);
expect(global.i18n.t).toHaveBeenCalledWith('string_id');
});
});
…生成此快照:

exports[`Component should render and call global.i18n.t() 1`] = `
<div>
  <h2>
    global.18n.t() called with string_id
  </h2>
</div>
`;
exports[`组件应该呈现并调用global.i18n.t()1`]=`
使用字符串\u id调用global.18n.t()
`;
请注意,快照测试正在使用和,这将生成格式良好的快照