Skip to content
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

[WIP] add useTreatment hook #70

Draft
wants to merge 1 commit into
base: development
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/__tests__/testUtils/mockSplitSdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,9 @@ function mockClient(key: SplitIO.SplitKey, trafficType?: string) {
const getTreatmentsWithConfig: jest.Mock = jest.fn(() => {
return 'getTreatmentsWithConfig';
});
const getTreatmentWithConfig: jest.Mock = jest.fn(() => {
return 'getTreatmentWithConfig';
});
const ready: jest.Mock = jest.fn(() => {
return new Promise((res, rej) => {
if (__isReady__) res();
Expand Down Expand Up @@ -90,6 +93,7 @@ function mockClient(key: SplitIO.SplitKey, trafficType?: string) {

return Object.assign(Object.create(__emitter__), {
getTreatmentsWithConfig,
getTreatmentWithConfig,
track,
ready,
destroy,
Expand Down
125 changes: 125 additions & 0 deletions src/__tests__/useTreatment.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
import React from 'react';
import { mount } from 'enzyme';

/** Mocks */
import { mockSdk } from './testUtils/mockSplitSdk';
jest.mock('@splitsoftware/splitio', () => {
return { SplitFactory: mockSdk() };
});
import { SplitFactory as SplitSdk } from '@splitsoftware/splitio';
import { sdkBrowser } from './testUtils/sdkConfigs';
jest.mock('../constants', () => {
const actual = jest.requireActual('../constants');
return {
...actual,
getControlTreatmentsWithConfig: jest.fn(actual.getControlTreatmentsWithConfig),
};
});
import { getControlTreatmentsWithConfig } from '../constants';
const logSpy = jest.spyOn(console, 'log');

/** Test target */
import SplitFactory from '../SplitFactory';
import SplitClient from '../SplitClient';
import useTreatment from '../useTreatment';

describe('useTreatment', () => {

const splitName = 'split1';
const attributes = { att1: 'att1' };

test('returns the Treatment from the client at Split context updated by SplitFactory.', () => {
const outerFactory = SplitSdk(sdkBrowser);
let treatment;

mount(
<SplitFactory factory={outerFactory} >{
React.createElement(() => {
treatment = useTreatment(splitName, attributes);
return null;
})}</SplitFactory>,
);
const getTreatmentWithConfig: jest.Mock = (outerFactory.client() as any).getTreatmentWithConfig;
expect(getTreatmentWithConfig).toBeCalledWith(splitName, attributes);
expect(getTreatmentWithConfig).toHaveReturnedWith(treatment);
});

test('returns the Treatment from the client at Split context updated by SplitClient.', () => {
const outerFactory = SplitSdk(sdkBrowser);
let treatment;

mount(
<SplitFactory factory={outerFactory} >
<SplitClient splitKey='user2' >{
React.createElement(() => {
treatment = useTreatment(splitName, attributes);
return null;
})}
</SplitClient>
</SplitFactory>,
);
const getTreatmentWithConfig: jest.Mock = (outerFactory.client('user2') as any).getTreatmentWithConfig;
expect(getTreatmentWithConfig).toBeCalledWith(splitName, attributes);
expect(getTreatmentWithConfig).toHaveReturnedWith(treatment);
});

test('returns the Treatment from a new client given a splitKey.', () => {
const outerFactory = SplitSdk(sdkBrowser);
let treatment;

mount(
<SplitFactory factory={outerFactory} >{
React.createElement(() => {
treatment = useTreatment(splitName, attributes, 'user2');
return null;
})}
</SplitFactory>,
);
const getTreatmentWithConfig: jest.Mock = (outerFactory.client('user2') as any).getTreatmentWithConfig;
expect(getTreatmentWithConfig).toBeCalledWith(splitName, attributes);
expect(getTreatmentWithConfig).toHaveReturnedWith(treatment);
});

test('returns Control Treatment if invoked outside Split context.', () => {
let treatment;

mount(
React.createElement(
() => {
treatment = useTreatment(splitName, attributes);
return null;
}),
);
expect(getControlTreatmentsWithConfig).toBeCalledWith([splitName]);
expect(getControlTreatmentsWithConfig).toHaveReturnedWith({
split1: {
config: null,
treatment: 'control'
}
});
});

/**
* Input validation. Passing invalid split names or attributes while the Sdk
* is not ready doesn't emit errors, and logs meaningful messages instead.
*/
test('Input validation: invalid "name" and "attributes" params in useTreatment.', (done) => {
mount(
React.createElement(
() => {
// @ts-ignore
let treatment = useTreatment('split1');
expect(treatment).toEqual({});
// @ts-ignore
treatment = useTreatment([true]);
expect(treatment).toEqual({});
return null;
}),
);
expect(logSpy).toBeCalledWith('[ERROR] split names must be a non-empty array.');
expect(logSpy).toBeCalledWith('[ERROR] you passed an invalid split name, split name must be a non-empty string.');

done();
});

});
20 changes: 20 additions & 0 deletions src/useTreatment.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import useClient from './useClient';
import { getControlTreatmentsWithConfig, ERROR_UT_NO_USECONTEXT } from './constants';
import { checkHooks } from './utils';

/**
* 'useTreatment' is a custom hook that returns a treatment for a given split.
* It uses the 'useContext' hook to access the client from the Split context,
* and invokes the 'getTreatmentWithConfig' method.
*
* @return A TreatmentWithConfig instance, that might contain the control treatment if the client is not available or ready, or if split name does not exist.
* @see {@link https://help.split.io/hc/en-us/articles/360020448791-JavaScript-SDK#get-treatments-with-configurations}
*/
const useTreatment = (splitName: string, attributes?: SplitIO.Attributes, key?: SplitIO.SplitKey): SplitIO.TreatmentWithConfig => {
const client = checkHooks(ERROR_UT_NO_USECONTEXT) ? useClient(key) : null;
return client ?
client.getTreatmentWithConfig(splitName, attributes) :
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ideally, I'd use client.getTreatment here instead, then I'd also have a useTreatmentWithConfig hook that uses client.getTreatmentWithConfig. Are we okay with me making that addition?

getControlTreatmentsWithConfig([splitName])[0];
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wanted to reuse the existing methods here, but I don't love passing in an array of a single item and returning the first entry.

I could expose validateSplit and create a new getControlTreatmentWithConfig that uses validateSplit instead of validateSplits.

Thoughts?

};

export default useTreatment;