Testing with formatjs
linzhaoqiang opened this issue · 8 comments
When I tested the class component using enzyme + jest, I found that the component rendered the result I wanted, using the format*() method of injectIntl in the react-intl library.
import React from 'react';
import {injectIntl, IntlProvider} from 'react-intl'
import { mount, shallow } from 'enzyme';
import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
const defaultLocale = 'en'
const locale = defaultLocale
function mountWithIntl(node) {
return mount(node, {
wrappingComponent: IntlProvider,
wrappingComponentProps: {
locale,
defaultLocale,
messages: {},
},
})
}
function shallowWithIntl(node) {
return shallow(node, {
wrappingComponent: IntlProvider,
wrappingComponentProps: {
locale,
defaultLocale,
messages: {},
},
})
}
Enzyme.configure({
adapter: new Adapter()
});
class Func extends React.Component {
render() {
return <div>{int.formatMessage({id:'xxx'})}</div>
}
}
const Component = injectIntl(Func);
describe('Name of the group', () => {
it('should ', () => {
const component = shallowWithIntl(<Component/>);
expect(component.find('div').length).toBe(1);
console.log(component);
});
});
FAIL src/App.test.js
Name of the group
× should (15ms)
● Name of the group › should
expect(received).toBe(expected) // Object.is equality
Expected: 1
Received: 0
45 | it('should ', () => {
46 | const component = shallowWithIntl(<Component/>);
> 47 | expect(component.find('div').length).toBe(1);
| ^
48 | console.log(component);
49 | });
50 | });
at Object.<anonymous> (src/App.test.js:47:42)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 4.275s
Api
- shallow
Version
library | version |
---|---|
enzyme | 3.11.0 |
react | 16.10.2 |
react-dom | 16.10.2 |
Adapter
- enzyme-adapter-react-16
What is component.debug()
?
console.log src/App.test.js:48
<ContextConsumer>
[function]
</ContextConsumer>
ok, so since it's shallow, it looks like you need another .dive()
there - it needs one .dive()
per HOC.
I tried component.dive().debug()
and returned <Func intl...}} />
and still couldn't find the element I wanted
and component.dive().dive().debug()
?
Oh, it works, but there's only one HOC. Why do you need two dive()
?
because there's obviously more than one HOC :-) injectIntl
must use two, not one, and that implementation detail isn't something enzyme can hide.
OK, thank you very much for your patience. 👍 :-)