Question
React SDK works only on client side (browser). When using Jest to run unit tests, the script runs on server mode only. Is there a way to test the SDK in browser mode?
Answer
As stated, the React SDK supports only Browser side. To force Jest to run in browser, we need to add the section below to package.json
{
"name": "MYAPP",
"version": "X.X.X",
....
"jest": {
"browser": true
}
...
}
The solution above works for React SDK version 1.2.4 and above.
For React SDK 1.2.3 and below, and if the app was created using create-react-app tool, this configuration will be rejected. The only workaround is to eject the app using the command below:
yarn eject
Note: Please keep in mind that once you eject the app, you will need to manage the dependencies manually.
The script below is a test example, the SDK runs in localhost mode and passes the split definitions using the features config parameter. Note that a wrapper object is used to load the generated html page, in the initial load the SDK props are not updated yet, so we need to run wrapper.update() to reload the page with the SDK props updated.
import React from "react";
import { act } from "react-dom/test-utils";
import Enzyme, { mount } from "enzyme";
import Adapter from "enzyme-adapter-react-16";
import { SplitFactory, SplitTreatments } from "@splitsoftware/splitio-react";
Enzyme.configure({ adapter: new Adapter() });
describe("switchio isReady minimal test case", () => {
const expectedText = "on";
const notReadyText = "Not Ready";
const feature_1 = 'clients';
const config = {
core: {
authorizationKey: "localhost",
key: 'react-user',
},
features: {
'clients': 'on',
'sample_features': 'off'
},
scheduler: {
offlineRefreshRate: 15
},
debug: true,
};
it("is ready", async () => {
let wrapper;
await act(async () => {
wrapper = mount(
<SplitFactory config={config} updateOnSdkTimedout={true}>
<SplitTreatments names={[feature_1]}>
{({ treatments, isReady }) =>
isReady
? treatments.clients.treatment
: notReadyText
}
</SplitTreatments>
</SplitFactory>
);
});
expect(wrapper.html().includes(expectedText)).toBe(false);
expect(wrapper.html().includes(notReadyText)).toBe(true);
wrapper.update();
expect(wrapper.html().includes(expectedText)).toBe(true);
expect(wrapper.html().includes(notReadyText)).toBe(false);
});
});
Comments
0 comments
Please sign in to leave a comment.