Skip to content

Commit

Permalink
add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
wangcheng committed Dec 3, 2024
1 parent 7587ff7 commit a353869
Show file tree
Hide file tree
Showing 4 changed files with 117 additions and 79 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"packages/example-mina"
],
"scripts": {
"test": "yarn workspace connect-miniprogram jest",
"build": "yarn workspace connect-miniprogram build",
"dev:taro": "yarn workspace example-taro dev:weapp"
},
Expand Down
24 changes: 16 additions & 8 deletions packages/connect-miniprogram/src/connect/async-generator.spec.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,34 @@
import { describe, expect, jest, test } from '@jest/globals';

import { fireEventQueue } from '../test-utils';
import { createAsyncGeneratorFromEventPattern } from './async-generator';

describe('createAsyncGeneratorFromEventPattern', () => {
const dispose = jest.fn();
test('creates am async generator', async () => {
const gen = createAsyncGeneratorFromEventPattern<number>(
({ handleValue, handleEnd }) => {
setTimeout(() => {
handleValue(1);
setTimeout(() => {
fireEventQueue([
() => {
handleValue(0);
},
() => {
handleValue(1);
},
() => {
handleValue(2);
setTimeout(() => {
handleEnd();
}, 0);
}, 0);
}, 0);
},
() => {
handleEnd();
},
]);
return dispose;
},
);
const a = gen();
expect(dispose).toBeCalledTimes(0);
expect(await a.next()).toEqual({ value: 0, done: false });
expect(dispose).toBeCalledTimes(0);
expect(await a.next()).toEqual({ value: 1, done: false });
expect(dispose).toBeCalledTimes(0);
expect(await a.next()).toEqual({ value: 2, done: false });
Expand Down
87 changes: 16 additions & 71 deletions packages/connect-miniprogram/src/connect/wx-request.spec.ts
Original file line number Diff line number Diff line change
@@ -1,83 +1,18 @@
import { describe, expect, jest, test } from '@jest/globals';

import { mockWxRequest } from '../test-utils';
import {
createWxRequestAsAsyncGenerator,
createWxRequestAsPromise,
} from './wx-request';

jest.mock('../protocol/envelope', () => ({
jest.mock('./envelope', () => ({
createEnvelopeAsyncGenerator: (s) => s,
}));

function typedArrayToBuffer(arr: Uint8Array) {
const length = arr.length;
const buffer = new ArrayBuffer(length);
const bufView = new Uint8Array(buffer);
for (let i = 0; i < length; i++) {
bufView[i] = arr[i];
}
return buffer;
}

const mockWxRequest = (noHeader: boolean = false) =>
jest.fn((options: WechatMiniprogram.RequestOption) => {
let chunkReceivedHandler: undefined | ((res: any) => void);
let headersReceivedHandler: undefined | ((res: any) => void);
const headerData: Partial<WechatMiniprogram.RequestSuccessCallbackResult> =
{
header: {
'response-header-key': 'response-header-value',
},
statusCode: 200,
cookies: [],
};
if (options.enableChunked) {
setTimeout(() => {
if (!noHeader) {
headersReceivedHandler?.(headerData);
}
setTimeout(() => {
chunkReceivedHandler?.({
data: typedArrayToBuffer(new Uint8Array([1, 2, 3])),
});
setTimeout(() => {
chunkReceivedHandler?.({
data: typedArrayToBuffer(new Uint8Array([4, 5, 6])),
});
options.success?.(
{} as WechatMiniprogram.RequestSuccessCallbackResult,
);
}, 0);
}, 0);
}, 0);
} else {
setTimeout(() => {
options.success?.({
...headerData,
data: typedArrayToBuffer(new Uint8Array([1, 2, 3, 4, 5, 6])),
} as WechatMiniprogram.RequestSuccessCallbackResult);
}, 0);
}
return {
abort: jest.fn(),
onChunkReceived: jest.fn((fn: (res: any) => void) => {
chunkReceivedHandler = fn;
}),
offChunkReceived: jest.fn(() => {
chunkReceivedHandler = undefined;
}),
onHeadersReceived: jest.fn((fn: (res: any) => void) => {
headersReceivedHandler = fn;
}),
offHeadersReceived: jest.fn(() => {
headersReceivedHandler = undefined;
}),
} as WechatMiniprogram.RequestTask;
}) as typeof wx.request;

describe('createWxRequestAsPromise', () => {
test('should return a promise, using binary format', () => {
const wxRequest = mockWxRequest();
const wxRequest = mockWxRequest({});
const request = createWxRequestAsPromise(
{
request: wxRequest,
Expand Down Expand Up @@ -112,7 +47,11 @@ describe('createWxRequestAsPromise', () => {

describe('createWxRequestAsAsyncGenerator', () => {
test('should return an async generator, not devtool', async () => {
const wxRequest = mockWxRequest();
const wxRequest = mockWxRequest({
responseHeader: {
'response-header-key': 'response-header-value',
},
});
const request = createWxRequestAsAsyncGenerator({
request: wxRequest,
isDevTool: false,
Expand Down Expand Up @@ -163,7 +102,11 @@ describe('createWxRequestAsAsyncGenerator', () => {
});

test('should return an async generator, is devtool', async () => {
const wxRequest = mockWxRequest();
const wxRequest = mockWxRequest({
responseHeader: {
'response-header-key': 'response-header-value',
},
});
const request = createWxRequestAsAsyncGenerator({
request: wxRequest,
isDevTool: true,
Expand Down Expand Up @@ -208,7 +151,9 @@ describe('createWxRequestAsAsyncGenerator', () => {
});

test('should throw if first chunk is not header', async () => {
const wxRequest = mockWxRequest(true);
const wxRequest = mockWxRequest({
skipHeadersReceivedHandler: true,
});
const request = createWxRequestAsAsyncGenerator({
request: wxRequest,
isDevTool: false,
Expand Down
84 changes: 84 additions & 0 deletions packages/connect-miniprogram/src/test-utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import { jest } from '@jest/globals';

function wait() {
return new Promise((resolve) => setTimeout(resolve, 0));
}

export async function fireEventQueue(fns: (() => void)[]) {
for (const fn of fns) {
await wait();
fn();
}
}

function buffer(arr: number[]) {
return new Uint8Array(arr).buffer;
}

export const mockWxRequest = ({
responseHeader = {},
skipHeadersReceivedHandler = false,
}: {
responseHeader?: Record<string, string>;
skipHeadersReceivedHandler?: boolean;
}) => {
const headerData: Partial<WechatMiniprogram.RequestSuccessCallbackResult> = {
header: responseHeader,
statusCode: 200,
cookies: [],
};
return jest.fn((options: WechatMiniprogram.RequestOption) => {
let chunkReceivedHandler: undefined | ((res: any) => void);
let headersReceivedHandler: undefined | ((res: any) => void);

if (options.enableChunked) {
const eventQueue = [
() => {
if (!skipHeadersReceivedHandler) {
headersReceivedHandler?.(headerData);
}
},
() => {
chunkReceivedHandler?.({
data: buffer([1, 2, 3]),
});
},
() => {
chunkReceivedHandler?.({
data: buffer([4, 5, 6]),
});
},
() => {
options.success?.(
{} as WechatMiniprogram.RequestSuccessCallbackResult,
);
},
];
fireEventQueue(eventQueue);
} else {
fireEventQueue([
() => {
options.success?.({
...headerData,
data: buffer([1, 2, 3, 4, 5, 6]),
} as WechatMiniprogram.RequestSuccessCallbackResult);
},
]);
}
return {
abort: jest.fn(),
onChunkReceived: jest.fn((fn: (res: any) => void) => {
chunkReceivedHandler = fn;
}),
offChunkReceived: jest.fn(() => {
chunkReceivedHandler = undefined;
}),
onHeadersReceived: jest.fn((fn: (res: any) => void) => {
headersReceivedHandler = fn;
}),
offHeadersReceived: jest.fn(() => {
headersReceivedHandler = undefined;
}),
} as WechatMiniprogram.RequestTask;
}) as typeof wx.request;
};

0 comments on commit a353869

Please sign in to comment.