谷歌分析已添加到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>
);
}
在进行单元测试的上面的代码中,它说“无法读取未定义的属性”。所以有什么方法可以将它初始化为start.Moreover 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';
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');
});
});
...制作这个快照:
exports[`Component should render and call global.i18n.t() 1`] = `
<div>
<h2>
global.18n.t() called with string_id
</h2>
</div>
`;
请注意,快照测试使用的是enzyme和enzyme-to-json,它们可以生成格式正确的快照。