-
Notifications
You must be signed in to change notification settings - Fork 2.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
测试时提示:formatMessage not initialized yet, you should use it after react app mounted #2156
Comments
测试时组件顶层没有国际化 context 的 provider ,目前比较简单的方法是 mock 掉 formatMessage |
@imhele 有空可以写下如何 mock 掉 formatMessage,很多人应该都不会。 |
我解决了,新建了一个intlHelper.js文件,在往component注入intl的同时,调用umi locale的_setIntlObject来初始化umi的intl。这样就不会在mount的过程中报错说formatMessage没有初始化了。但是这种做法可能不被支持,毕竟_setIntlObject是umi内部函数。
在渲染component时直接调用即可 参考了: |
或许可以在 umi-plugin-locale 中添加 |
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions. |
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions. |
现在可用的mock formatMessage 的方案: import React from 'react';
import { mount } from 'enzyme';
import { formatMessage } from 'umi-plugin-react/locale';
import { MyComponent } from '../../src/component';
import messages from '../../src/locale/en-US';
jest.mock('umi-plugin-react/locale');
describe('component/MyComponent.test.js', () => {
it('MyComponent', async () => {
formatMessage.mockImplementation(({ id }) => {
return <span>{messages[id]}</span>;
});
const wrapper = mount(<MyComponent />);
const html = wrapper.html();
expect(html).toMatch(/My translation/);
});
}); |
|
在单元测试中,使用enzyme初始化含有formatMessage方法的组件时,无论使用mount或者shallow:
mount(<Component {...props} />
都会在umi-plugin-locale出现warning:
有没有解决办法在测试中解决这个warning?
The text was updated successfully, but these errors were encountered: