Jest doesn't officially support requirejs.
How should we test a Webpart which has a dependency to an amd module (i.e. PeoplePicker) with Jest framework?
Webpart which imports the React PeoplePicker. Test fails with error Cannot find module 'ControlStrings' from 'PeoplePickerComponent.js'
import * as React from 'react';
import { PeoplePicker } from "@pnp/spfx-controls-react/lib/PeoplePicker";
export default class JestTest extends React.Component<any, any> {
public render(): React.ReactElement<any> {
return (
<div>
<h1>People Picker</h1>
<PeoplePicker context={null} titleText="Title" />
</div>
);
}
}
/// <reference types="jest" />
import * as React from 'react';
import { configure, mount, ReactWrapper } from 'enzyme';
import * as Adapter from 'enzyme-adapter-react-15';
import JestTest from '../components/JestTest';
configure({ adapter: new Adapter() });
describe('Enzyme basics', () => {
let reactComponent: ReactWrapper<any, any>;
beforeEach(() => {
reactComponent = mount(React.createElement(JestTest));
});
it('should has the correct title', () => {
let cssSelector: string = 'h1';
const text = reactComponent.find(cssSelector).text();
expect(text).toBe("People Picker");
});
});
So, I'm going to answer my question by myself:
As a workaround we mock components which can not be handled by jest.
Example: Mock PeoplePicker
jest.mock('@pnp/spfx-controls-react/lib/PeoplePicker', () => 'PeoplePicker');
And then use the ShallowWrapper from enzyme:
let reactComponent: ShallowWrapper<any, any>;
...
reactComponent = shallow(<JestTest/>);
This leads to a bunch of mocks but works in our case.
Hopefully Jest would support AMD Modules soon and spfx react 16 ;-)
thanks, @christianbueschi for following up with the answer as well, so closing this one.
Issues that have been closed & had no follow-up activity for at least 7 days are automatically locked. Please refer to our wiki for more details, including how to remediate this action if you feel this was done prematurely or in error: Issue List: Our approach to locked issues
Most helpful comment
So, I'm going to answer my question by myself:
As a workaround we mock components which can not be handled by jest.
Example: Mock PeoplePicker
And then use the ShallowWrapper from enzyme:
This leads to a bunch of mocks but works in our case.
Hopefully Jest would support AMD Modules soon and spfx react 16 ;-)