From 8b90f47e034db5285f9cc6fec6c03f9e4521f2aa Mon Sep 17 00:00:00 2001 From: Filippo De Santis Date: Mon, 23 May 2022 17:35:07 +0200 Subject: [PATCH] docs: Add documentation for reply accepting a function as the data parameter (#1456) * Add a small paragraph documenting reply accept a function as the data parameter * Update docs/best-practices/mocking-request.md Co-authored-by: Frazer Smith Co-authored-by: Frazer Smith --- docs/best-practices/mocking-request.md | 32 ++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/docs/best-practices/mocking-request.md b/docs/best-practices/mocking-request.md index ebcc90d24b7..b98a450a32e 100644 --- a/docs/best-practices/mocking-request.md +++ b/docs/best-practices/mocking-request.md @@ -101,4 +101,36 @@ const badRequest = await bankTransfer('1234567890', '100') // subsequent request to origin http://localhost:3000 was not allowed (net.connect disabled) ``` +## Reply with data based on request +If the mocked response needs to be dynamically derived from the request parameters, you can provide a function instead of an object to `reply` + +```js +mockPool.intercept({ + path: '/bank-transfer', + method: 'POST', + headers: { + 'X-TOKEN-SECRET': 'SuperSecretToken', + }, + body: JSON.stringify({ + recepient: '1234567890', + amount: '100' + }) +}).reply(200, (opts) => { + // do something with opts + + return { message: 'transaction processed' } +}) +``` + +in this case opts will be + +``` +{ + method: 'POST', + headers: { 'X-TOKEN-SECRET': 'SuperSecretToken' }, + body: '{"recepient":"1234567890","amount":"100"}', + origin: 'http://localhost:3000', + path: '/bank-transfer' +} +```