Skip to content

Commit 0037c32

Browse files
committed
Mock server: allow supplying a callback for generating the wanted response based on the request
1 parent 423bd8a commit 0037c32

File tree

1 file changed

+15
-7
lines changed

1 file changed

+15
-7
lines changed

src/tests/mock-server.ts

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,10 @@ const DEFAULT_MOCK_SERVER_OPTIONS: MockServerOptions = {
124124
reportMissingListeners: true,
125125
}
126126

127+
type MockRequestResponseDataObject<DataT extends object | undefined> = Omit<RequestSuccessResponse<DataT>, 'callback_id'> | Omit<RequestErrorResponse, 'callback_id'>;
128+
type MockRequestResponseDataHandler<DataT extends object | undefined> = (request: OutgoingRequest, s: WebSocket) => MockRequestResponseDataObject<DataT>;
129+
type MockRequestResponseData<DataT extends object | undefined> = MockRequestResponseDataObject<DataT> | MockRequestResponseDataHandler<DataT>;
130+
127131
const getMockServer = (initialOptions: Partial<MockServerOptions> = {}) => {
128132
const { url, reportMissingListeners }: MockServerOptions = {
129133
...DEFAULT_MOCK_SERVER_OPTIONS,
@@ -141,7 +145,7 @@ const getMockServer = (initialOptions: Partial<MockServerOptions> = {}) => {
141145
const addServerHandler = <DataT extends object | undefined>(
142146
method: string,
143147
path: string,
144-
responseData: Omit<RequestSuccessResponse<DataT>, 'callback_id'> | Omit<RequestErrorResponse, 'callback_id'>,
148+
responseData: MockRequestResponseData<DataT>,
145149
subscriptionCallback?: Callback
146150
) => {
147151
emitter.addListener(
@@ -151,9 +155,10 @@ const getMockServer = (initialOptions: Partial<MockServerOptions> = {}) => {
151155
subscriptionCallback(request);
152156
}
153157

158+
const data = typeof responseData === 'function' ? responseData(request, s) : responseData;
154159
const response: RequestSuccessResponse | RequestErrorResponse = {
155160
callback_id: request.callback_id,
156-
...responseData,
161+
...data,
157162
};
158163

159164
s.send(JSON.stringify(response));
@@ -173,15 +178,18 @@ const getMockServer = (initialOptions: Partial<MockServerOptions> = {}) => {
173178
const addRequestHandler = <DataT extends object | undefined>(
174179
method: string,
175180
path: string,
176-
data?: DataT,
181+
data?: DataT | MockRequestResponseDataHandler<DataT>,
177182
subscriptionCallback?: Callback
178183
) => {
184+
const handlerData = typeof data === 'function' ? data : {
185+
data,
186+
code: data ? 200 : 204,
187+
}
188+
179189
addServerHandler<DataT>(
180190
method,
181-
path, {
182-
data,
183-
code: 200,
184-
},
191+
path,
192+
handlerData,
185193
subscriptionCallback
186194
);
187195
}

0 commit comments

Comments
 (0)