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

chore: refactored fetch to use Platform.requests. Removed jest-fetch-mock. #297

Merged
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
2 changes: 2 additions & 0 deletions packages/shared/mocks/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@ import clientContext from './clientContext';
import ContextDeduplicator from './contextDeduplicator';
import { crypto, hasher } from './hasher';
import logger from './logger';
import mockFetch from './mockFetch';
import basicPlatform from './platform';
import { MockStreamingProcessor, setupMockStreamingProcessor } from './streamingProcessor';

export {
basicPlatform,
clientContext,
mockFetch,
crypto,
logger,
hasher,
Expand Down
32 changes: 32 additions & 0 deletions packages/shared/mocks/src/mockFetch.ts
Copy link
Contributor Author

Choose a reason for hiding this comment

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

@kinyoklion please re-review I have improved the mockFetch implementation so it's easier to use. Thank you.

Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { Response } from '@common';

import basicPlatform from './platform';

const createMockResponse = (remoteJson: any, statusCode: number) => {
const response: Response = {
headers: {
get: jest.fn(),
keys: jest.fn(),
values: jest.fn(),
entries: jest.fn(),
has: jest.fn(),
},
status: statusCode,
text: jest.fn(),
json: () => Promise.resolve(remoteJson),
};
return Promise.resolve(response);
};

/**
* Mocks basicPlatform fetch. Returns the fetch jest.Mock object.
* @param remoteJson
* @param statusCode
*/
const mockFetch = (remoteJson: any, statusCode: number = 200): jest.Mock => {
const f = basicPlatform.requests.fetch as jest.Mock;
f.mockResolvedValue(createMockResponse(remoteJson, statusCode));
return f;
};

export default mockFetch;
3 changes: 0 additions & 3 deletions packages/shared/sdk-client/jest-setupFilesAfterEnv.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1 @@
import '@testing-library/jest-dom';
import fetchMock from 'jest-fetch-mock';

fetchMock.enableMocks();
1 change: 0 additions & 1 deletion packages/shared/sdk-client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@
"jest": "^29.6.1",
"jest-diff": "^29.6.1",
"jest-environment-jsdom": "^29.6.1",
"jest-fetch-mock": "^3.0.3",
yusinto marked this conversation as resolved.
Show resolved Hide resolved
"launchdarkly-js-test-helpers": "^2.2.0",
"prettier": "^3.0.0",
"ts-jest": "^29.1.1",
Expand Down
30 changes: 15 additions & 15 deletions packages/shared/sdk-client/src/evaluation/fetchFlags.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import fetchMock from 'jest-fetch-mock';

import { LDContext } from '@launchdarkly/js-sdk-common';
import { basicPlatform } from '@launchdarkly/private-js-mocks';
import { basicPlatform, mockFetch } from '@launchdarkly/private-js-mocks';

import Configuration from '../configuration';
import fetchFlags from './fetchFlags';
Expand All @@ -24,21 +22,21 @@ describe('fetchFeatures', () => {
};

let config: Configuration;
const platformFetch = basicPlatform.requests.fetch as jest.Mock;

beforeEach(() => {
fetchMock.mockOnce(JSON.stringify(mockResponse));
mockFetch(mockResponse);
config = new Configuration();
});

afterEach(() => {
fetchMock.resetMocks();
jest.resetAllMocks();
});

test('get', async () => {
const json = await fetchFlags(sdkKey, context, config, basicPlatform);

expect(fetchMock).toBeCalledWith(
expect(platformFetch).toBeCalledWith(
'https://sdk.launchdarkly.com/sdk/evalx/testSdkKey1/contexts/eyJraW5kIjoidXNlciIsImtleSI6InRlc3QtdXNlci1rZXktMSJ9',
{
method: 'GET',
Expand All @@ -52,21 +50,23 @@ describe('fetchFeatures', () => {
config = new Configuration({ useReport: true });
const json = await fetchFlags(sdkKey, context, config, basicPlatform);

expect(fetchMock).toBeCalledWith('https://sdk.launchdarkly.com/sdk/evalx/testSdkKey1/context', {
method: 'REPORT',
headers: reportHeaders,
body: '{"kind":"user","key":"test-user-key-1"}',
});
expect(platformFetch).toBeCalledWith(
'https://sdk.launchdarkly.com/sdk/evalx/testSdkKey1/context',
{
method: 'REPORT',
headers: reportHeaders,
body: '{"kind":"user","key":"test-user-key-1"}',
},
);
expect(json).toEqual(mockResponse);
});

test('withReasons', async () => {
fetchMock.resetMocks();
fetchMock.mockOnce(JSON.stringify(mockResponseWithReasons));
mockFetch(mockResponseWithReasons);
config = new Configuration({ withReasons: true });
const json = await fetchFlags(sdkKey, context, config, basicPlatform);

expect(fetchMock).toBeCalledWith(
expect(platformFetch).toBeCalledWith(
'https://sdk.launchdarkly.com/sdk/evalx/testSdkKey1/contexts/eyJraW5kIjoidXNlciIsImtleSI6InRlc3QtdXNlci1rZXktMSJ9?withReasons=true',
{
method: 'GET',
Expand All @@ -80,7 +80,7 @@ describe('fetchFeatures', () => {
config = new Configuration({ hash: 'test-hash', withReasons: false });
const json = await fetchFlags(sdkKey, context, config, basicPlatform);

expect(fetchMock).toBeCalledWith(
expect(platformFetch).toBeCalledWith(
'https://sdk.launchdarkly.com/sdk/evalx/testSdkKey1/contexts/eyJraW5kIjoidXNlciIsImtleSI6InRlc3QtdXNlci1rZXktMSJ9?h=test-hash',
{
method: 'GET',
Expand Down
11 changes: 4 additions & 7 deletions packages/shared/sdk-client/src/evaluation/fetchFlags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,15 @@ export type Flags = {
[k: string]: Flag;
};

/**
* Dom api usage: fetch.
*/
const fetchFlags = async (
sdkKey: string,
context: LDContext,
config: Configuration,
platform: Platform,
{ encoding, info, requests }: Platform,
): Promise<Flags> => {
const fetchUrl = createFetchUrl(sdkKey, context, config, platform.encoding!);
const fetchOptions: RequestInit = createFetchOptions(sdkKey, context, config, platform.info);
const response = await fetch(fetchUrl, fetchOptions);
const fetchUrl = createFetchUrl(sdkKey, context, config, encoding!);
const fetchOptions = createFetchOptions(sdkKey, context, config, info);
const response = await requests.fetch(fetchUrl, fetchOptions);
yusinto marked this conversation as resolved.
Show resolved Hide resolved
return response.json();
};

Expand Down
6 changes: 2 additions & 4 deletions packages/shared/sdk-client/src/evaluation/fetchUtils.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import { defaultHeaders, Encoding, Info, LDContext } from '@launchdarkly/js-sdk-common';
import { defaultHeaders, Encoding, Info, LDContext, Options } from '@launchdarkly/js-sdk-common';

import Configuration from '../configuration';

/**
* Dom api usage: btoa.
*
* In react-native use base64-js to polyfill btoa. This is safe
* because the react-native repo uses it too. Set the global.btoa to the encode
* function of base64-js.
Expand Down Expand Up @@ -69,7 +67,7 @@ export const createFetchOptions = (
context: LDContext,
config: Configuration,
info: Info,
): RequestInit => {
): Options => {
const { useReport, tags } = config;
const headers = defaultHeaders(sdkKey, info, tags);

Expand Down