zedevs
zedevs
CDCloudflare Developers
Created by zedevs on 7/10/2023 in #workers-help
Mocking fetch
Hi folks, I've been looking for a way to mock outgoing fetch net requests and I've hit a brick wall with everything I could dig up. I am using wrangler v3.0.1 and have the following files:
// jest.config.js
const { defaults } = require("jest-config");

module.exports = {
preset: 'ts-jest',
testEnvironment: "miniflare",
moduleFileExtensions: ["mjs", ...defaults.moduleFileExtensions],
};
// jest.config.js
const { defaults } = require("jest-config");

module.exports = {
preset: 'ts-jest',
testEnvironment: "miniflare",
moduleFileExtensions: ["mjs", ...defaults.moduleFileExtensions],
};
// src/worker.ts

export default {
async fetch(cfRequest: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
const url = new URL('https://example.com');
return sendRequestToAPI(url, { bodyStuff: 'here' }, env, cfRequest, ctx);
const resp = await fetch('example.com');
},
};
// src/worker.ts

export default {
async fetch(cfRequest: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
const url = new URL('https://example.com');
return sendRequestToAPI(url, { bodyStuff: 'here' }, env, cfRequest, ctx);
const resp = await fetch('example.com');
},
};
// src/helpers.ts
export const sendToApi = async (
url: URL,
body: any,
env: Env,
cfRequest: Request,
ctx: ExecutionContext
): Promise<Response> => {
const request = {
body: JSON.stringify(body),
method: 'POST'
};
const response = await fetch(url, request);
if (response.status !== 200) {
return new Response('Bad', { status: 500 });
} else {
return new response('Good', {status: 200});
}
}
// src/helpers.ts
export const sendToApi = async (
url: URL,
body: any,
env: Env,
cfRequest: Request,
ctx: ExecutionContext
): Promise<Response> => {
const request = {
body: JSON.stringify(body),
method: 'POST'
};
const response = await fetch(url, request);
if (response.status !== 200) {
return new Response('Bad', { status: 500 });
} else {
return new response('Good', {status: 200});
}
}
... continues in a comment due to discord message length limits...
3 replies