Skip to content

Crawlee—A web scraping and browser automation library for Node.js to build reliable crawlers. In JavaScript and TypeScript. Extract data for AI, LLMs, RAG, or GPTs. Download HTML, PDF, JPG, PNG, and other files from websites. Works with Puppeteer, Playwright, Cheerio, JSDOM, and raw HTTP. Both headful and headless mode. With proxy rotation.

67.4 KB
Raw Blame
import { createServer, type Server } from 'node:http';
import type { AddressInfo } from 'node:net';

import type { BasicCrawlingContext, CheerioCrawlingContext, CheerioRequestHandler, Source } from '@crawlee/cheerio';
import { FetchHttpClient } from '@crawlee/http-client';
import {
    CheerioCrawler,
    createCheerioRouter,
    EnqueueStrategy,
    mergeCookies,
    ProxyConfiguration,
    Request,
    RequestList,
    Session,
} from '@crawlee/cheerio';
import { type ConcurrencySystem, SessionPool } from '@crawlee/basic';
import { BaseCrawleeLogger, MemoryStorageBackend, serviceLocator } from '@crawlee/core';
import { BaseHttpClient } from '@crawlee/http-client';
import { ImpitHttpClient } from '@crawlee/impit-client';
import type { Dictionary, ISession, ProxyInfo, SendRequestOptions } from '@crawlee/types';
import { sleep } from '@crawlee/utils';
import iconv from 'iconv-lite';
import { CookieJar } from 'tough-cookie';
import { responseSamples, runExampleComServer } from '../../shared/_helper.js';

import log from '@apify/log';

let server: Server;
let port: number;
let serverAddress = 'http://localhost:';

async function getRequestListForMock(mockData: Dictionary, pathName = 'special/mock') {
    const sources: Source[] = [1, 2, 3, 4].map((num) => {
        return {
            url: `${serverAddress}/${pathName}?a=${num}`,
            payload: JSON.stringify(mockData),
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
        };
    });
    const requestList = await RequestList.open(null, sources);
    return requestList;
}

async function getExampleRequestList(pathname = '/special/mirror') {
    const sources = [
        { url: `${serverAddress}${pathname}?a=12` },
        { url: `${serverAddress}${pathname}?a=23` },
        { url: `${serverAddress}${pathname}?a=33` },
        { url: `${serverAddress}${pathname}?a=43` },
    ];
    const requestList = await RequestList.open(null, sources);
    return requestList;
}

beforeAll(async () => {
    [server, port] = await runExampleComServer();
    serverAddress += port;
});

afterEach(() => {
    vi.useRealTimers();
});

afterAll(() => {
    server.close();
});

describe('CheerioCrawler', () => {
    let logLevel: number;

    beforeAll(async () => {
        logLevel = log.getLevel();
        log.setLevel(log.LEVELS.ERROR);
    });

    beforeEach(async () => {
        serviceLocator.setStorageBackend(new MemoryStorageBackend());
    });

    afterAll(async () => {
        log.setLevel(logLevel);
    });

    test('should work', async () => {
        const requestList = await getExampleRequestList();
        const processed: Request[] = [];
        const failed: Request[] = [];
        const requestHandler: CheerioRequestHandler = ({ $, body, request }) => {
            request.userData.title = $('title').text();
            request.userData.body = body;
            processed.push(request);
        };

        const cheerioCrawler = new CheerioCrawler({
            requestList,
            minConcurrency: 2,
            maxConcurrency: 2,
            requestHandler,
            failedRequestHandler: ({ request }) => {
                failed.push(request);
            },
        });

        await cheerioCrawler.run();

        expect((cheerioCrawler.concurrencySystem! as ConcurrencySystem).minConcurrency).toBe(2);
        expect(processed).toHaveLength(4);
        expect(failed).toHaveLength(0);

        processed.forEach((request) => {
            expect(request.userData.title).toBe('Title');
            expect(typeof request.userData.body).toBe('string');
            expect((request.userData.body as string).length).not.toBe(0);
        });
    });

    test('should work with implicit router', async () => {
        const requestList = await getExampleRequestList();
        const processed: Request[] = [];
        const failed: Request[] = [];

        const cheerioCrawler = new CheerioCrawler({
            requestList,
            minConcurrency: 2,
            maxConcurrency: 2,
            failedRequestHandler: ({ request }) => {
                failed.push(request);
            },
        });

        cheerioCrawler.router.addDefaultHandler<{ title: string; body: string }>(({ $, body, request }) => {
            request.userData.title = $('title').text();
            request.userData.body = body.toString();
            processed.push(request);
        });

        await cheerioCrawler.run();

        expect((cheerioCrawler.concurrencySystem! as ConcurrencySystem).minConcurrency).toBe(2);
        expect(processed).toHaveLength(4);
        expect(failed).toHaveLength(0);

        processed.forEach((request) => {
            expect(request.userData.title).toBe('Title');
            expect(typeof request.userData.body).toBe('string');
            expect((request.userData.body as string).length).not.toBe(0);
        });
    });

    test('should work with explicit router', async () => {
        const requestList = await getExampleRequestList();
        const processed: Request[] = [];
        const failed: Request[] = [];

        const router = createCheerioRouter<CheerioCrawlingContext<{ title: string; body: string }>>();

        const cheerioCrawler = new CheerioCrawler({
            requestHandler: router,
            requestList,
            minConcurrency: 2,
            maxConcurrency: 2,
            failedRequestHandler: ({ request }) => {
                failed.push(request);
            },
        });

        router.addDefaultHandler(({ $, body, request }) => {
            request.userData.title = $('title').text();
            request.userData.body = body.toString();
            processed.push(request);
        });

        await cheerioCrawler.run();

        expect((cheerioCrawler.concurrencySystem! as ConcurrencySystem).minConcurrency).toBe(2);
        expect(processed).toHaveLength(4);
        expect(failed).toHaveLength(0);

        processed.forEach((request) => {
            expect(request.userData.title).toBe('Title');
            expect(typeof request.userData.body).toBe('string');
            expect((request.userData.body as string).length).not.toBe(0);
        });
    });

    test('should throw when no requestHandler nor default route provided', async () => {
        const requestList = await getExampleRequestList();

        const cheerioCrawler = new CheerioCrawler({
            requestList,
            minConcurrency: 2,
            maxConcurrency: 2,
        });

        await expect(cheerioCrawler.run()).rejects.toThrow(
            "Route not found for label 'undefined'. You must set up a route for this label or a default route. Use `requestHandler`, `router.addHandler` or `router.addDefaultHandler`.",
        );
    });

    test('forwards ignoreTlsErrors to the http client', async () => {
        const captured: (boolean | undefined)[] = [];
        const fetchClient = new FetchHttpClient();
        // Carries the BaseHttpClient prototype so the crawler's `z.instanceof` validation accepts it.
        const capturingClient = Object.assign(Object.create(BaseHttpClient.prototype) as BaseHttpClient, {
            sendRequest: async (request: globalThis.Request, options?: { ignoreTlsErrors?: boolean }) => {
                captured.push(options?.ignoreTlsErrors);
                return fetchClient.sendRequest(request, options);
            },
        });

        const defaultCrawler = new CheerioCrawler({
            httpClient: capturingClient,
            maxConcurrency: 1,
            requestHandler: () => {},
        });
        await defaultCrawler.run([`${serverAddress}/?tls=default`]);

        const strictCrawler = new CheerioCrawler({
            httpClient: capturingClient,
            ignoreTlsErrors: false,
            maxConcurrency: 1,
            requestHandler: () => {},
        });
        await strictCrawler.run([`${serverAddress}/?tls=strict`]);

        const lenientCrawler = new CheerioCrawler({
            httpClient: capturingClient,
            ignoreTlsErrors: true,
            maxConcurrency: 1,
            requestHandler: () => {},
        });
        await lenientCrawler.run([`${serverAddress}/?tls=lenient`]);

        expect(captured).toEqual([false, false, true]);
    });

    test('should work with skipNavigation', async () => {
        const processed: Request[] = [];
        const failed: Request[] = [];

        const cheerioCrawler = new CheerioCrawler({
            maxConcurrency: 1,
            requestHandler: ({ request }) => {
                processed.push(request);
            },
            failedRequestHandler: ({ request }) => {
                failed.push(request);
            },
        });

        await cheerioCrawler.run([
            {
                url: 'http://example.com/',
                skipNavigation: true,
            },
        ]);

        expect(processed).toHaveLength(1);
        expect(failed).toHaveLength(0);
    });

    test('should work with not encoded urls', async () => {
        const sources = [
            { url: `${serverAddress}/mirror?q=abc` },
            { url: `${serverAddress}/mirror?q=%` },
            { url: `${serverAddress}/mirror?q=%cf` },
        ];
        const requestList = await RequestList.open(null, sources);
        const processed: Request[] = [];
        const failed: Request[] = [];
        const requestHandler: CheerioRequestHandler = ({ $, body, request }) => {
            request.userData.title = $('title').text();
            request.userData.body = body;
            processed.push(request);
        };

        const cheerioCrawler = new CheerioCrawler({
            requestList,
            minConcurrency: 2,
            maxConcurrency: 2,
            requestHandler,
            failedRequestHandler: ({ request }) => {
                failed.push(request);
            },
        });

        await cheerioCrawler.run();

        expect(processed).toHaveLength(3);
        expect(failed).toHaveLength(0);

        const sorted = processed.map((r) => r.loadedUrl).sort();
        expect(sorted).toEqual([
            `${serverAddress}/mirror?q=%`,
            `${serverAddress}/mirror?q=%cf`,
            `${serverAddress}/mirror?q=abc`,
        ]);
    });

    test('should serialize body and html', async () => {
        const sources = [`${serverAddress}/special/html-type`];
        const requestList = await RequestList.open(null, sources);
        const tmp: any[] = [];

        const cheerioCrawler = new CheerioCrawler({
            requestList,
            maxRequestRetries: 0,
            maxConcurrency: 1,
            requestHandler: ({ $, body, request }) => {
                // test that `request.loadedUrl` is no longer optional by calling `toLowerCase` on it directly (no optional chaining)
                tmp.push(body, $.html(), request.loadedUrl.toLowerCase());
            },
        });

        await cheerioCrawler.run();

        expect(tmp).toHaveLength(3);
        expect(tmp[0]).toBe(responseSamples.html);
        expect(tmp[1]).toBe(tmp[0]);
        expect(tmp[2].length).toBe(sources[0].length);
    });

    describe('should timeout', () => {
        let ll: number;
        beforeAll(() => {
            ll = log.getLevel();
            log.setLevel(log.LEVELS.OFF);
        });

        afterAll(() => {
            log.setLevel(ll);
        });

        test('after navigationTimeoutSecs', async () => {
            const sources = [
                { url: 'http://example.com/?q=0' },
                { url: 'http://example.com/?q=1' },
                { url: 'http://example.com/?q=2' },
            ];
            const processed: Request[] = [];
            const failed: Request[] = [];
            const requestList = await RequestList.open(null, sources);
            const requestHandler: CheerioRequestHandler = ({ request }) => {
                processed.push(request);
            };

            // a client that always outlives the navigation window; carries the BaseHttpClient prototype so
            // the crawler's `z.instanceof` validation accepts it
            const slowClient = Object.assign(Object.create(BaseHttpClient.prototype) as BaseHttpClient, {
                sendRequest: async () => {
                    await sleep(300);
                    return new Response('<html><head></head><body>Body</body></html>', {
                        headers: { 'content-type': 'text/html' },
                    });
                },
            });

            const cheerioCrawler = new CheerioCrawler({
                requestList,
                httpClient: slowClient,
                navigationTimeoutSecs: 5 / 1000,
                maxRequestRetries: 1,
                minConcurrency: 2,
                maxConcurrency: 2,
                requestHandler,
                failedRequestHandler: ({ request }) => {
                    failed.push(request);
                },
            });

            await cheerioCrawler.run();

            expect(processed).toHaveLength(0);
            expect(failed).toHaveLength(3);

            failed.forEach((request) => {
                expect(request.errorMessages).toHaveLength(2);
                expect(request.errorMessages[0]).toMatch('Navigation timed out');
                expect(request.errorMessages[1]).toMatch('Navigation timed out');
            });
        });

        test('after requestHandlerTimeoutSecs', async () => {
            const failed: Request[] = [];
            const requestList = await getExampleRequestList();
            const requestHandler = vi.fn(async () => {
                await sleep(2000);
            });

            const cheerioCrawler = new CheerioCrawler({
                requestList,
                requestHandlerTimeoutSecs: 1,
                maxRequestRetries: 1,
                minConcurrency: 2,
                maxConcurrency: 2,
                requestHandler,
                failedRequestHandler: ({ request }) => {
                    failed.push(request);
                },
            });

            await cheerioCrawler.run();

            expect(requestHandler).toHaveBeenCalledTimes(8);
            expect(failed).toHaveLength(4);

            failed.forEach((request) => {
                expect(request).toEqual(
                    expect.objectContaining({
                        errorMessages: [
                            expect.stringContaining('requestHandler timed out'),
                            expect.stringContaining('requestHandler timed out'),
                        ],
                    }),
                );
            });
        });

        test('when a pre-navigation hook exceeds the navigation window', async () => {
            const failed: Request[] = [];
            const requestList = await getExampleRequestList();
            const requestHandler = vi.fn();

            const cheerioCrawler = new CheerioCrawler({
                requestList,
                navigationTimeoutSecs: 0.1,
                maxRequestRetries: 1,
                minConcurrency: 2,
                maxConcurrency: 2,
                preNavigationHooks: [async () => sleep(2000)],
                requestHandler,
                failedRequestHandler: ({ request }) => {
                    failed.push(request);
                },
            });

            await cheerioCrawler.run();

            expect(requestHandler).not.toHaveBeenCalled();
            expect(failed).toHaveLength(4);

            failed.forEach((request) => {
                expect(request.errorMessages).toHaveLength(2);

                request.errorMessages.forEach((message) => {
                    // a hook overrunning shares the navigation window, so it reads as a navigation timeout
                    expect(message).toMatch('Navigation timed out');
                    // ...not the request handler, which is timed separately
                    expect(message).not.toMatch('requestHandler timed out');
                });
            });
        });

        test('after navigationTimeoutSecs in a post-navigation hook', async () => {
            const failed: Request[] = [];
            const requestList = await getExampleRequestList();
            const requestHandler = vi.fn();

            const cheerioCrawler = new CheerioCrawler({
                requestList,
                navigationTimeoutSecs: 0.1,
                maxRequestRetries: 1,
                minConcurrency: 2,
                maxConcurrency: 2,
                postNavigationHooks: [async () => sleep(2000)],
                requestHandler,
                failedRequestHandler: ({ request }) => {
                    failed.push(request);
                },
            });

            await cheerioCrawler.run();

            expect(requestHandler).not.toHaveBeenCalled();
            expect(failed).toHaveLength(4);

            failed.forEach((request) => {
                request.errorMessages.forEach((message) => {
                    expect(message).toMatch('Navigation timed out');
                });
            });
        });

        test('navigation hooks that finish in time do not affect the handler timeout', async () => {
            const processed: Request[] = [];
            const requestList = await getExampleRequestList();

            const cheerioCrawler = new CheerioCrawler({
                requestList,
                // the hooks eat 300ms in total, which must not be charged to the 1s handler window
                navigationTimeoutSecs: 1,
                requestHandlerTimeoutSecs: 1,
                maxRequestRetries: 0,
                minConcurrency: 2,
                maxConcurrency: 2,
                preNavigationHooks: [async () => sleep(150)],
                postNavigationHooks: [async () => sleep(150)],
                requestHandler: async ({ request }) => {
                    await sleep(700);
                    processed.push(request);
                },
            });

            await cheerioCrawler.run();

            expect(processed).toHaveLength(4);
        });

        test('extendTimeout from a pre-navigation hook keeps it from timing out', async () => {
            const processed: Request[] = [];
            const failed: Request[] = [];
            const requestList = await getExampleRequestList();

            const cheerioCrawler = new CheerioCrawler({
                requestList,
                navigationTimeoutSecs: 0.2,
                maxRequestRetries: 0,
                minConcurrency: 2,
                maxConcurrency: 2,
                // 400ms total, past the 0.2s window - only survives because the hook asks for more time
                preNavigationHooks: [
                    async ({ extendTimeout }) => {
                        await sleep(100);
                        extendTimeout(5);
                        await sleep(300);
                    },
                ],
                requestHandler: async ({ request }) => {
                    processed.push(request);
                },
                failedRequestHandler: ({ request }) => {
                    failed.push(request);
                },
            });

            await cheerioCrawler.run();

            expect(failed).toHaveLength(0);
            expect(processed).toHaveLength(4);
        });

        test('extendTimeout from a post-navigation hook keeps it from timing out', async () => {
            const processed: Request[] = [];
            const failed: Request[] = [];
            const requestList = await getExampleRequestList();

            const cheerioCrawler = new CheerioCrawler({
                requestList,
                // enough for the (fast, local) navigation, but far short of the hook below
                navigationTimeoutSecs: 1,
                maxRequestRetries: 0,
                minConcurrency: 2,
                maxConcurrency: 2,
                postNavigationHooks: [
                    async ({ extendTimeout }) => {
                        // the navigation already spent part of the shared window, so ask for more up front,
                        // then take far longer than the window would otherwise have allowed
                        extendTimeout(5);
                        await sleep(2000);
                    },
                ],
                requestHandler: async ({ request }) => {
                    processed.push(request);
                },
                failedRequestHandler: ({ request }) => {
                    failed.push(request);
                },
            });

            await cheerioCrawler.run();

            expect(failed).toHaveLength(0);
            expect(processed).toHaveLength(4);
        });

        test('navigationTimeoutSecs bounds a slowly-streamed response body', async () => {
            // the headers arrive at once, but the body dribbles out over ~5s - reading it is still part of the
            // navigation, so it must be bound by `navigationTimeoutSecs` rather than run unbounded
            const slowServer = createServer(async (_req, res) => {
                res.writeHead(200, { 'content-type': 'text/html', 'content-length': '20' });
                for (let i = 0; i < 20; i++) {
                    res.write('x');
                    await sleep(250);
                }
                res.end();
            });
            await new Promise<void>((resolve) => slowServer.listen(0, resolve));
            const { port: slowPort } = slowServer.address() as import('node:net').AddressInfo;

            try {
                const processed: Request[] = [];
                const failed: Request[] = [];
                const requestList = await RequestList.open(null, [{ url: `http://localhost:${slowPort}/` }]);

                const cheerioCrawler = new CheerioCrawler({
                    requestList,
                    navigationTimeoutSecs: 1,
                    maxRequestRetries: 0,
                    httpClient: new FetchHttpClient(),
                    requestHandler: ({ request }) => {
                        processed.push(request);
                    },
                    failedRequestHandler: ({ request }) => {
                        failed.push(request);
                    },
                });

                const startedAt = Date.now();
                await cheerioCrawler.run();

                expect(processed).toHaveLength(0);
                expect(failed).toHaveLength(1);
                expect(failed[0].errorMessages[0]).toMatch('Navigation timed out');
                // it must give up around the 1s window, not wait out the whole ~5s body
                expect(Date.now() - startedAt).toBeLessThan(3000);
            } finally {
                slowServer.close();
            }
        });

        test('stops downloading a response body that outlives the navigation window', async () => {
            let closed = false;
            const endlessServer = createServer((_req, res) => {
                res.writeHead(200, { 'content-type': 'text/html' });
                const interval = setInterval(() => res.write('x'.repeat(1024)), 10);
                res.on('close', () => {
                    clearInterval(interval);
                    closed = true;
                });
            });
            await new Promise<void>((resolve) => endlessServer.listen(0, resolve));
            const { port: endlessPort } = endlessServer.address() as AddressInfo;

            try {
                const failed: Request[] = [];
                const cheerioCrawler = new CheerioCrawler({
                    navigationTimeoutSecs: 1,
                    maxRequestRetries: 0,
                    httpClient: new ImpitHttpClient(),
                    requestHandler: () => {},
                    failedRequestHandler: ({ request }) => {
                        failed.push(request);
                    },
                });

                await cheerioCrawler.run([`http://localhost:${endlessPort}/`]);

                expect(failed).toHaveLength(1);
                await vi.waitFor(() => expect(closed).toBe(true), { timeout: 2000 });
            } finally {
                endlessServer.closeAllConnections();
                endlessServer.close();
            }
        });
    });

    describe('should not timeout by the default httpRequest timeoutSecs', () => {
        it('when navigationTimeoutSecs is greater than 30', async () => {
            const sources = [{ url: `${serverAddress}/timeout?a=12` }, { url: `${serverAddress}/timeout?a=23` }];
            const processed: Request[] = [];
            const failed: Request[] = [];
            const requestList = await RequestList.open(null, sources);
            const requestHandler: CheerioRequestHandler = ({ request }) => {
                processed.push(request);
            };

            const cheerioCrawler = new CheerioCrawler({
                requestList,
                maxRequestRetries: 1,
                navigationTimeoutSecs: 35,
                minConcurrency: 2,
                maxConcurrency: 2,
                requestHandler,
                failedRequestHandler: ({ request }) => {
                    failed.push(request);
                },
            });

            await cheerioCrawler.run();

            expect(processed).toHaveLength(2);
            expect(failed).toHaveLength(0);
        }, 40000);
    });

    describe('should ensure text/html Content-Type', () => {
        test('by setting a correct Accept header', async () => {
            const headersPerRequests: Headers[] = [];
            const requestList = await getExampleRequestList('/special/headers');
            const crawler = new CheerioCrawler({
                requestList,
                requestHandler: async ({ json }) => {
                    headersPerRequests.push(new Headers(json.headers));
                },
            });

            await crawler.run();
            expect(headersPerRequests).toHaveLength(4);
            headersPerRequests.forEach((headerset) => {
                const acceptHeader = headerset.get('accept');
                expect(acceptHeader!.includes('text/html')).toBe(true);
                expect(acceptHeader!.includes('application/xhtml+xml')).toBe(true);
            });
        });

        describe('by throwing', () => {
            let crawler;
            let handlePageInvocationCount = 0;
            let errorMessages: string[] = [];

            beforeEach(() => {
                log.setLevel(log.LEVELS.OFF);
            });
            afterEach(async () => {
                log.setLevel(log.LEVELS.ERROR);
                crawler = null;
                handlePageInvocationCount = 0;
                errorMessages = [];
            });

            test('when invalid Content-Type header is received', async () => {
                // Mock Request to inject invalid response headers.

                crawler = new CheerioCrawler({
                    requestList: await getRequestListForMock({
                        headers: {
                            'content-type': 'text/plain',
                        },
                        statusCode: 200,
                    }),
                    maxRequestRetries: 1,
                    requestHandler: () => {
                        handlePageInvocationCount++;
                    },
                    failedRequestHandler: ({ request }) => {
                        errorMessages = [...errorMessages, ...request.errorMessages];
                    },
                });

                await crawler.run();

                expect(handlePageInvocationCount).toBe(0);
                expect(errorMessages).toHaveLength(4);
                errorMessages.forEach((msg) =>
                    expect(msg).toMatch(
                        ' Content-Type text/plain, but only text/html, text/xml, application/xhtml+xml, application/xml, application/json are allowed.' +
                            ' Skipping resource.',
                    ),
                );
            });

            test('when statusCode >= 500 and text/html is received', async () => {
                // sometimes if you get blocked you can get 500+ with some html inside
                crawler = new CheerioCrawler({
                    requestList: await getRequestListForMock({
                        statusCode: 508,
                        headers: {
                            'content-type': 'text/html',
                        },
                        body: 'DATABASE ERROR',
                    }),
                    maxRequestRetries: 1,
                    requestHandler: () => {
                        handlePageInvocationCount++;
                    },
                    failedRequestHandler: ({ request }) => {
                        errorMessages = [...errorMessages, ...request.errorMessages];
                    },
                });
                await crawler.run();

                expect(handlePageInvocationCount).toBe(0);
                expect(errorMessages).toHaveLength(8);
                errorMessages.forEach((msg) => expect(msg).toMatch('Internal Server Error'));
            });

            test('when statusCode >= 500 and application/json is received', async () => {
                crawler = new CheerioCrawler({
                    requestList: await getRequestListForMock({}, 'special/jsonError'),
                    maxRequestRetries: 1,
                    requestHandler: () => {
                        handlePageInvocationCount++;
                    },
                    failedRequestHandler: ({ request }) => {
                        errorMessages = [...errorMessages, ...request.errorMessages];
                    },
                });
                await crawler.run();

                expect(handlePageInvocationCount).toBe(0);
                expect(errorMessages).toHaveLength(8);
                errorMessages.forEach((msg) => expect(msg).toMatch('CUSTOM_ERROR'));
            });
        });
    });

    test('should ignore http error status codes set by user', async () => {
        const requestList = await getRequestListForMock({
            headers: {
                'content-type': 'text/plain',
            },
            statusCode: 500,
        });

        const failed: Request[] = [];

        const cheerioCrawler = new CheerioCrawler({
            requestList,
            minConcurrency: 2,
            maxConcurrency: 2,
            ignoreHttpErrorStatusCodes: [500],
            requestHandler: () => {},
            failedRequestHandler: ({ request }) => {
                failed.push(request);
            },
        });

        await cheerioCrawler.run();

        expect((cheerioCrawler.concurrencySystem! as ConcurrencySystem).minConcurrency).toBe(2);
        expect(failed).toHaveLength(0);
    });

    test('should throw an error on http error status codes set by user', async () => {
        const requestList = await getExampleRequestList();
        const failed: Request[] = [];

        const cheerioCrawler = new CheerioCrawler({
            requestList,
            minConcurrency: 2,
            maxConcurrency: 2,
            additionalHttpErrorStatusCodes: [200],
            requestHandler: () => {},
            failedRequestHandler: ({ request }) => {
                failed.push(request);
            },
        });

        await cheerioCrawler.run();

        expect((cheerioCrawler.concurrencySystem! as ConcurrencySystem).minConcurrency).toBe(2);
        expect(failed).toHaveLength(4);
    });

    test('should work with all defaults content types', async () => {
        let handledRequests = 0;
        const contentTypes = ['text/html', 'application/xhtml+xml', 'text/xml', 'application/xml', 'application/json'];
        const sources: Source[] = contentTypes.map((contentType) => ({
            url: `${serverAddress}/mock?ct=${contentType}`,
            payload: JSON.stringify({ headers: { 'Content-Type': contentType }, statusCode: 200 }),
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
        }));
        const requestList = await RequestList.open({
            sources,
        });
        const crawler = new CheerioCrawler({
            requestList,
            requestHandler: () => {
                handledRequests++;
            },
        });
        await crawler.run();
        expect(handledRequests).toEqual(contentTypes.length);
    });

    describe('should work with all content types from options.additionalMimeTypes', () => {
        let handlePageInvocationParams: CheerioCrawlingContext;
        let handleFailedInvoked = false;
        const runCrawler = async (url: string) => {
            const sources = [url];
            const requestList = await RequestList.open(null, sources);
            const crawler = new CheerioCrawler({
                requestList,
                additionalMimeTypes: ['application/json', 'image/png', 'application/xml'],
                maxRequestRetries: 1,
                requestHandler: (params) => {
                    handlePageInvocationParams = params;
                },
                failedRequestHandler: () => {
                    handleFailedInvoked = true;
                },
            });
            await crawler.run();
        };

        test('when response is application/json', async () => {
            const url = `${serverAddress}/special/json-type`;
            await runCrawler(url);
            expect(handlePageInvocationParams.json).toBeInstanceOf(Object);
            expect(handlePageInvocationParams.body).toEqual(JSON.stringify(responseSamples.json));
            expect(handlePageInvocationParams.contentType.type).toBe('application/json');
            expect(handleFailedInvoked).toBe(false);
        });
        test('when response is application/xml', async () => {
            const url = `${serverAddress}/special/xml-type`;
            await runCrawler(url);
            expect(typeof handlePageInvocationParams.body).toBe('string');
            expect(handlePageInvocationParams.body).toEqual(responseSamples.xml);
            expect(handlePageInvocationParams.$).toBeInstanceOf(Function);
            expect(handlePageInvocationParams.contentType.type).toBe('application/xml');
        });
        test('when response is image/png', async () => {
            const url = `${serverAddress}/special/image-type`;
            await runCrawler(url);
            expect(typeof handlePageInvocationParams.body).toBe('string');
            expect(handlePageInvocationParams.body).toEqual(responseSamples.image.toString());
            expect(handlePageInvocationParams.contentType.type).toBe('image/png');
        });
    });

    describe('should use response encoding', () => {
        const html = '<html>Žluťoučký kůň</html>';
        // serves the very same windows-1250 bytes, with the charset in the content-type header only when asked
        let encodingServer: Server;
        let encodingServerUrl: string;

        beforeAll(async () => {
            encodingServer = createServer((req, res) => {
                const charset = new URL(req.url!, 'http://localhost').searchParams.get('charset');
                res.writeHead(200, { 'content-type': `text/html${charset ? `; charset=${charset}` : ''}` });
                res.end(iconv.encode(html, 'windows-1250'));
            });
            await new Promise<void>((resolve) => encodingServer.listen(0, resolve));
            const { port: encodingPort } = encodingServer.address() as AddressInfo;
            encodingServerUrl = `http://localhost:${encodingPort}`;
        });

        afterAll(() => {
            encodingServer.close();
        });

        test('as a fallback', async () => {
            // Ensure it's really encoded.
            expect(iconv.encode(html, 'windows-1250').toString('utf8')).not.toBe(html);

            let context: CheerioCrawlingContext | null = null;
            const crawler = new CheerioCrawler({
                requestHandler: (ctx) => {
                    context = ctx;
                },
                suggestResponseEncoding: 'windows-1250',
            });

            await crawler.run([encodingServerUrl]);

            context = context as unknown as CheerioCrawlingContext;
            expect(context.body).toBe(html);
            expect(context.$('html').text()).toBe('Žluťoučký kůň');
        });

        test('always when forced', async () => {
            let context: CheerioCrawlingContext | null = null;
            const crawler = new CheerioCrawler({
                requestHandler: (ctx) => {
                    context = ctx;
                },
                forceResponseEncoding: 'win1250',
            });

            // the header says ascii, the bytes are windows-1250 - the forced encoding must win
            await crawler.run([`${encodingServerUrl}/?charset=ascii`]);

            context = context as unknown as CheerioCrawlingContext;
            expect(context.contentType.encoding).toBe('utf8');
            expect(context.body).toBe(html);
        });

        test('via http-equiv meta tag when no charset in HTTP header', async () => {
            let context: CheerioCrawlingContext | null = null;

            const crawler = new CheerioCrawler({
                requestHandler: (ctx) => {
                    context = ctx;
                },
            });

            await crawler.run([`${serverAddress}/special/meta-charset`]);

            context = context as unknown as CheerioCrawlingContext;
            expect(context?.body).toContain('Žluťoučký kůň');
            expect(context?.$('body').text()).toContain('Žluťoučký kůň');
        });

        test('Cheerio decodes html entities', async () => {
            let context: CheerioCrawlingContext | null = null;

            const crawler = new CheerioCrawler({
                requestHandler: (ctx) => {
                    context = ctx;
                },
            });

            await crawler.run([`${serverAddress}/special/html-entities`]);

            context = context as unknown as CheerioCrawlingContext;
            expect(context?.$.html()).toBe('&quot;&lt;&gt;&quot;&lt;&gt;');
            expect(context?.$.html({ xml: { decodeEntities: false, xmlMode: false } })).toBe('"<>"<>');
            expect(context?.body).toBe('&quot;&lt;&gt;"<>');
        });
    });

    describe('proxy', () => {
        beforeEach(async () => {
            // Do not use clearAllMocks: https://github.com/facebook/vitest/issues/7136
            vitest.restoreAllMocks();
        });

        test('should work with Apify Proxy configuration', async () => {
            const proxyUrl = serverAddress;
            const proxyConfiguration = new ProxyConfiguration({
                proxyUrls: [proxyUrl],
            });

            const requestList = await getExampleRequestList();

            const proxies: string[] = [];
            const crawler = new CheerioCrawler({
                requestList,
                requestHandler: ({ proxyInfo }) => {
                    proxies.push(proxyInfo!.url);
                },
                proxyConfiguration,
            });

            await crawler.run();

            expect(proxies[0]).toEqual(proxyUrl);
            expect(proxies[1]).toEqual(proxyUrl);
            expect(proxies[2]).toEqual(proxyUrl);
            expect(proxies[3]).toEqual(proxyUrl);
        });

        test('requestHandler should expose the proxyInfo object with sessions correctly', async () => {
            const proxyUrls = [0, 1, 2, 3].map((n) => `${serverAddress}/proxy?x=${n}`);
            const proxyConfiguration = new ProxyConfiguration({
                proxyUrls,
            });

            const proxies: ProxyInfo[] = [];
            const sessions: ISession[] = [];
            const requestHandler = ({ session, proxyInfo }: CheerioCrawlingContext) => {
                proxies.push(proxyInfo!);
                sessions.push(session!);
            };

            const requestList = await getExampleRequestList();

            const crawler = new CheerioCrawler({
                requestList,
                requestHandler,
                proxyConfiguration,
            });

            await crawler.run();

            for (let i = 0; i < 4; i++) {
                const proxyInfo = proxies[i];
                const session = sessions[i];
                expect(typeof proxyInfo.url).toBe('string');
                expect(typeof session.id).toBe('string');
                expect(session.proxyInfo).toBe(proxyInfo);
            }
        });

        test('proxy rotation on error works as expected', async () => {
            const goodProxyUrl = 'http://good.proxy';
            const proxyConfiguration = new ProxyConfiguration({
                proxyUrls: ['http://localhost', 'http://localhost:1234', goodProxyUrl],
            });
            const check = vitest.fn();
            const impit = new ImpitHttpClient();

            const crawler = new CheerioCrawler({
                maxRequestRetries: 2,
                maxConcurrency: 1,

                proxyConfiguration,
                requestHandler: () => {},
                httpClient: Object.assign(Object.create(BaseHttpClient.prototype) as BaseHttpClient, {
                    sendRequest: async (request: globalThis.Request, opts?: SendRequestOptions) => {
                        const proxyUrl = opts?.session?.proxyInfo?.url;
                        check({ ...opts, proxyUrl });

                        if (proxyUrl === goodProxyUrl) {
                            return await impit.sendRequest(request);
                        }

                        throw new Error('Proxy responded with 400 - Bad request');
                    },
                }),
            });

            await expect(crawler.run([serverAddress])).resolves.not.toThrow();
            expect(check).toBeCalledWith(expect.objectContaining({ proxyUrl: goodProxyUrl }));
        });

        test('proxy rotation on error respects maxRequestRetries, calls failedRequestHandler', async () => {
            const proxyConfiguration = new ProxyConfiguration({
                proxyUrls: ['http://localhost', 'http://localhost:1234'],
            });

            /**
             * The first increment is the base case when the proxy is retrieved for the first time.
             */
            let numberOfRotations = -1;
            const failedRequestHandler = vitest.fn();
            const impit = new ImpitHttpClient();
            const crawler = new CheerioCrawler({
                proxyConfiguration,
                maxRequestRetries: 5,
                requestHandler: async () => {},
                failedRequestHandler,
                httpClient: Object.assign(Object.create(BaseHttpClient.prototype) as BaseHttpClient, {
                    sendRequest: async (request: globalThis.Request, opts?: SendRequestOptions) => {
                        const { session } = opts ?? {};
                        if (session?.proxyInfo?.url.includes('localhost')) {
                            numberOfRotations++;
                            throw new Error('Proxy responded with 400 - Bad request');
                        }
                        return await impit.sendRequest(request);
                    },
                }),
            });

            await crawler.run([serverAddress]);
            expect(failedRequestHandler).toBeCalledTimes(1);
            expect(numberOfRotations).toBe(5);
        });

        test('proxy rotation logs the original proxy error', async () => {
            const proxyConfiguration = new ProxyConfiguration({ proxyUrls: ['http://localhost:1234'] });

            const proxyError =
                'Proxy responded with 400 - Bad request. Also, this error message contains some useful payload.';

            const impit = new ImpitHttpClient();

            const crawler = new CheerioCrawler({
                proxyConfiguration,
                maxRequestRetries: 1,
                requestHandler: async () => {},
                httpClient: Object.assign(Object.create(BaseHttpClient.prototype) as BaseHttpClient, {
                    sendRequest: async (request: globalThis.Request, opts?: SendRequestOptions) => {
                        const { session } = opts ?? {};
                        if (session?.proxyInfo?.url.includes('localhost')) {
                            throw new Error(proxyError);
                        }
                        return impit.sendRequest(request);
                    },
                }),
            });

            const spy = vitest.spyOn((crawler as any).log, 'warning' as any).mockImplementation(() => {});

            await crawler.run([serverAddress]);

            expect(spy).toHaveBeenCalledWith(expect.stringContaining(proxyError), expect.any(Object));
        });
    });

    describe('SessionPool', () => {
        let requestList: RequestList;

        beforeEach(async () => {
            requestList = await RequestList.open(null, [serverAddress]);
        });

        test('should work', async () => {
            expect.assertions(1);
            const crawler = new CheerioCrawler({
                requestList,

                saveResponseCookies: false,
                requestHandler: ({ session }) => {
                    expect(session).toBeInstanceOf(Session);
                },
            });
            await crawler.run();
        });

        test('should correctly set session pool options', async () => {
            const sessionPool = new SessionPool({
                sessionOptions: {
                    maxUsageCount: 1,
                },
                persistStateKeyValueStoreId: 'abc',
            });

            const crawler = new CheerioCrawler({
                requestList,
                saveResponseCookies: false,
                sessionPool,
                requestHandler: () => {},
            });

            expect(crawler.sessionPool).toBe(sessionPool);
            const session = await sessionPool.getSession();
            expect(session).toBeDefined();
            const state = await sessionPool.getState();
            expect(state.sessions[0].maxUsageCount).toBe(1);
        });

        test('should markBad sessions after request timeout', async () => {
            // log.setLevel(log.LEVELS.OFF);
            const cheerioCrawler = new CheerioCrawler({
                requestList: await RequestList.open(null, [
                    `${serverAddress}/special/timeout?a=12`,
                    `${serverAddress}/special/timeout?a=23`,
                ]),
                maxRequestRetries: 1,
                navigationTimeoutSecs: 1,
                maxConcurrency: 1,

                requestHandler: async () => {
                    await sleep(1);
                },
            });

            await cheerioCrawler.run();

            const { sessions } = await (cheerioCrawler.sessionPool as SessionPool).getState();
            expect(sessions.length).toBe(4);
            sessions.forEach((session) => {
                // TODO this test is flaky in CI and we need some more info to debug why.
                if (session.errorScore !== 1) {
                    console.log('SESSIONS:');

                    console.dir(sessions);
                }

                // TODO too flaky
                // expect(session.errorScore).toEqual(1);
            });

            // log.setLevel(log.LEVELS.ERROR);
        });

        test('should retire session on "blocked" status codes', async () => {
            for (const code of [401, 403, 429]) {
                const failed: Request[] = [];
                const sessions: ISession[] = [];
                const maxRequestRetries = 5;
                const crawler = new CheerioCrawler({
                    requestList: await getRequestListForMock({
                        statusCode: code,
                        error: false,
                        headers: { 'Content-type': 'text/html' },
                    }),

                    saveResponseCookies: false,
                    maxRequestRetries,
                    requestHandler: ({ session }) => {
                        sessions.push(session);
                    },
                    failedRequestHandler: ({ request }) => {
                        failed.push(request);
                    },
                });
                await crawler.run();

                const { sessions: poolSessions } = await (crawler.sessionPool as SessionPool).getState();
                // each request retires its session on every retry, so we get
                // (maxRequestRetries + 1) sessions per request (retired ones + the final one)
                expect(poolSessions.length).toBe(4 * (maxRequestRetries + 1));

                poolSessions.forEach((session) => {
                    expect(session.errorScore).toBeGreaterThanOrEqual(session.maxErrorScore);
                });

                expect(failed.length).toBe(4);

                failed.forEach((request) => {
                    expect(
                        request.errorMessages[0].includes(`Request blocked - received ${code} status code`),
                    ).toBeTruthy();
                });
            }
        });

        test('should send cookies', async () => {
            const cookie = 'SESSID=abcd123';
            const requests: Request[] = [];
            const crawler = new CheerioCrawler({
                requestList: await getRequestListForMock(
                    {
                        headers: { 'set-cookie': cookie, 'content-type': 'text/html' },
                        statusCode: 200,
                    },
                    '/getRawHeaders',
                ),

                saveResponseCookies: true,
                sessionPool: new SessionPool({
                    maxPoolSize: 1,
                }),
                maxRequestRetries: 1,
                maxConcurrency: 1,
                requestHandler: ({ request }) => {
                    requests.push(request);
                },
            });

            await crawler.run();
            requests.forEach((_req, i) => {
                if (i >= 1) {
                    const response = JSON.parse(_req.payload!);

                    expect(response.headers['set-cookie']).toEqual(cookie);
                }
            });
        });

        test('should merge request and session cookies', async () => {
            const responses: unknown[] = [];
            const crawler = new CheerioCrawler({
                requestList: await RequestList.open(null, [
                    {
                        url: `${serverAddress}/special/headers`,
                        headers: { cookie: 'foo=bar2; baz=123' },
                    },
                ]),
                saveResponseCookies: false,
                sessionPool: new SessionPool({
                    maxPoolSize: 1,
                }),
                preNavigationHooks: [
                    async ({ session, request }) => {
                        // this should get overriden by the server
                        await session.cookieJar.setCookie('foo=bar1', request.url);
                        await session.cookieJar.setCookie('other=cookie1', request.url);

                        request.headers ??= {};
                        request.headers.cookie += '; coo=kie';
                    },
                ],
                requestHandler: ({ json }) => {
                    responses.push(json);
                },
            });

            await crawler.run();
            expect(responses).toHaveLength(1);
            expect(responses[0]).toMatchObject({
                headers: {
                    cookie: 'foo=bar2; other=cookie1; baz=123; coo=kie',
                },
            });
        });

        test('should work with cookies adjusted on `context.request` in pre-nav hook', async () => {
            const responses: unknown[] = [];
            const crawler = new CheerioCrawler({
                requestList: await RequestList.open(null, [
                    {
                        url: `${serverAddress}/special/headers`,
                        headers: { cookie: 'foo=bar2; baz=123' },
                    },
                ]),

                saveResponseCookies: false,
                sessionPool: new SessionPool({
                    maxPoolSize: 1,
                }),
                requestHandler: ({ json }) => {
                    responses.push(json);
                },
                preNavigationHooks: [
                    ({ request }) => {
                        request.headers!.Cookie = 'foo=override; coo=kie';
                    },
                ],
            });

            await crawler.run();
            expect(responses).toHaveLength(1);
            expect(responses[0]).toMatchObject({
                headers: {
                    cookie: 'foo=override; baz=123; coo=kie',
                },
            });
        });

        test('should work with `context.request.headers` being undefined', async () => {
            const requests: Request[] = [];
            const responses: unknown[] = [];
            const errorHandler = vi.fn(async () => {});

            const crawler = new CheerioCrawler({
                requestList: await RequestList.open(null, [
                    {
                        url: `${serverAddress}/special/headers`,
                    },
                ]),

                requestHandler: async ({ json, request }) => {
                    responses.push(json);
                    requests.push(request);
                },
                errorHandler,
                preNavigationHooks: [
                    ({ request }) => {
                        request.headers!.Cookie = 'foo=override; coo=kie';
                    },
                ],
            });

            await crawler.run();

            expect(errorHandler).not.toHaveBeenCalled();

            expect(requests).toHaveLength(1);
            expect(requests[0].retryCount).toBe(0);
            expect(responses).toHaveLength(1);
            expect(responses[0]).toMatchObject({
                headers: {
                    cookie: 'foo=override; coo=kie',
                },
            });
        });

        test('mergeCookies()', async () => {
            const warningSpy = vitest.spyOn(BaseCrawleeLogger.prototype, 'warningOnce');
            const cookie1 = mergeCookies('https://example.com', [
                'foo=bar1; other=cookie1 ; coo=kie',
                'foo=bar2; baz=123',
                'other=cookie2;foo=bar3',
            ]);
            expect(cookie1).toBe('foo=bar3; other=cookie2; coo=kie; baz=123');
            expect(warningSpy).not.toBeCalled();

            const cookie2 = mergeCookies('https://example.com', [
                'Foo=bar1; other=cookie1 ; coo=kie',
                'foo=bar2; baz=123',
                'Other=cookie2;foo=bar3',
            ]);
            expect(cookie2).toBe('Foo=bar1; other=cookie1; coo=kie; foo=bar3; baz=123; Other=cookie2');
            expect(warningSpy).toBeCalledTimes(3);
            expect(warningSpy).toBeCalledWith(`Found cookies with similar name during cookie merging: 'foo' and 'Foo'`);
            expect(warningSpy).toBeCalledWith(
                `Found cookies with similar name during cookie merging: 'Other' and 'other'`,
            );
            warningSpy.mockClear();

            const cookie3 = mergeCookies('https://example.com', [
                'foo=bar1; Other=cookie1 ; Coo=kie',
                'foo=bar2; baz=123',
                'Other=cookie2;Foo=bar3;coo=kee',
            ]);
            expect(cookie3).toBe('foo=bar2; Other=cookie2; Coo=kie; baz=123; Foo=bar3; coo=kee');
            expect(warningSpy).toBeCalledTimes(2);
            expect(warningSpy).toBeCalledWith(`Found cookies with similar name during cookie merging: 'Foo' and 'foo'`);
            expect(warningSpy).toBeCalledWith(`Found cookies with similar name during cookie merging: 'coo' and 'Coo'`);
        });

        test('mergeCookies() skips malformed cookie fragments instead of throwing', () => {
            const warningSpy = vitest.spyOn(BaseCrawleeLogger.prototype, 'warning');
            expect(mergeCookies('https://example.com', ['valid=1; brokenfragment'])).toBe('valid=1');
            expect(mergeCookies('https://example.com', ['a=b', 'c'])).toBe('a=b');
            expect(mergeCookies('https://example.com', ['sessionid'])).toBe('');
            expect(warningSpy).toBeCalled();
        });

        test('sendRequest and main request should share the same session cookie jar', async () => {
            const responses: { cookies: string }[] = [];

            const crawler = new CheerioCrawler({
                requestList: await RequestList.open(null, [{ url: `${serverAddress}/special/get-cookies` }]),

                sessionPool: new SessionPool({
                    // Even with multiple available sessions, the preNavigationHook should use the same one as the main request
                    maxPoolSize: 10,
                }),
                preNavigationHooks: [
                    async ({ sendRequest }) => {
                        await sendRequest({
                            url: `${serverAddress}/special/set-cookie?name=sharedCookie&value=sharedValue`,
                        });

                        const response = await sendRequest({ url: `${serverAddress}/special/get-cookies` });
                        const json = await response.json();

                        expect(json.cookies).toContain('sharedCookie=sharedValue');
                    },
                ],
                requestHandler: async ({ json, sendRequest }) => {
                    responses.push(json as { cookies: string });

                    const sendRequestJson = await sendRequest({ url: `${serverAddress}/special/get-cookies` }).then(
                        async (response) => response.json(),
                    );
                    responses.push(sendRequestJson as { cookies: string });
                },
            });

            await crawler.run();

            expect(responses).toHaveLength(2);
            expect(responses[0].cookies).toContain('sharedCookie=sharedValue');
            expect(responses[1].cookies).toContain('sharedCookie=sharedValue');
        });

        test('sendRequest should respect Cookie header override', async () => {
            const responses: { cookies: string }[] = [];

            const crawler = new CheerioCrawler({
                requestList: await RequestList.open(null, [
                    { url: `${serverAddress}/special/set-cookie?name=sessionCookie&value=fromSession` },
                ]),
                requestHandler: async ({ sendRequest }) => {
                    const withHeader = await sendRequest({
                        url: `${serverAddress}/special/get-cookies`,
                        headers: new Headers({ Cookie: 'custom=override' }),
                    });
                    responses.push((await withHeader.json()) as { cookies: string });

                    const withoutOverride = await sendRequest({
                        url: `${serverAddress}/special/get-cookies`,
                    });
                    responses.push((await withoutOverride.json()) as { cookies: string });
                },
            });

            await crawler.run();
            expect(responses).toHaveLength(2);
            expect(responses[0].cookies).toContain('custom=override');
            expect(responses[0].cookies).toContain('sessionCookie=fromSession');
            expect(responses[1].cookies).toContain('sessionCookie=fromSession');
            expect(responses[1].cookies).not.toContain('custom=override');
        });

        test('sendRequest should respect cookieJar override', async () => {
            const responses: { cookies: string }[] = [];

            const crawler = new CheerioCrawler({
                requestList: await RequestList.open(null, [
                    { url: `${serverAddress}/special/set-cookie?name=sessionCookie&value=fromSession` },
                ]),
                requestHandler: async ({ sendRequest }) => {
                    const customJar = new CookieJar();
                    await customJar.setCookie('jar=fromCustomJar', `${serverAddress}/special/get-cookies`);

                    const withJar = await sendRequest(
                        { url: `${serverAddress}/special/get-cookies` },
                        { cookieJar: customJar },
                    );
                    responses.push((await withJar.json()) as { cookies: string });

                    const withoutOverride = await sendRequest({ url: `${serverAddress}/special/get-cookies` });
                    responses.push((await withoutOverride.json()) as { cookies: string });
                },
            });

            await crawler.run();
            expect(responses).toHaveLength(2);
            expect(responses[0].cookies).toContain('jar=fromCustomJar');
            expect(responses[0].cookies).not.toContain('sessionCookie=fromSession');
            expect(responses[1].cookies).toContain('sessionCookie=fromSession');
            expect(responses[1].cookies).not.toContain('jar=fromCustomJar');
        });

        test('saveResponseCookies=false should not persist response cookies into the session', async () => {
            const sessionCookies: string[] = [];

            const crawler = new CheerioCrawler({
                sessionPool: new SessionPool({ maxPoolSize: 1 }),
                saveResponseCookies: false,
                maxConcurrency: 1,
                requestList: await RequestList.open(null, [
                    {
                        url: `${serverAddress}/special/set-cookie?name=responseCookie&value=fromResponse`,
                        uniqueKey: '1',
                    },
                    {
                        url: `${serverAddress}/special/set-cookie?name=responseCookie&value=fromResponse`,
                        uniqueKey: '2',
                    },
                ]),
                requestHandler: async ({ session, request }) => {
                    sessionCookies.push(await session.cookieJar.getCookieString(request.url));
                },
            });

            await crawler.run();
            expect(sessionCookies).toEqual(['', '']);
        });

        test('saveResponseCookies=false should still send session-set cookies to the request', async () => {
            const responses: { cookies: string }[] = [];

            const crawler = new CheerioCrawler({
                sessionPool: new SessionPool({ maxPoolSize: 1 }),
                saveResponseCookies: false,
                maxConcurrency: 1,
                requestList: await RequestList.open(null, [`${serverAddress}/special/get-cookies`]),
                preNavigationHooks: [
                    async ({ session, request }) => {
                        await session.cookieJar.setCookie('manual=fromHook', request.url);
                    },
                ],
                requestHandler: ({ json }) => {
                    responses.push(json as { cookies: string });
                },
            });

            await crawler.run();
            expect(responses).toHaveLength(1);
            expect(responses[0].cookies).toContain('manual=fromHook');
        });
    });

    describe('Crawling context', () => {
        let requestList: RequestList;
        let actualLogLevel: number;
        beforeEach(async () => {
            actualLogLevel = log.getLevel();
            log.setLevel(log.LEVELS.OFF);
            requestList = await RequestList.open(null, [serverAddress]);
        });

        afterAll(() => {
            log.setLevel(actualLogLevel);
        });

        test('uses correct crawling context', async () => {
            let prepareCrawlingContext: unknown;

            const preNavigationHook = (crawlingContext: BasicCrawlingContext) => {
                prepareCrawlingContext = crawlingContext;
                expect(crawlingContext.request).toBeInstanceOf(Request);
                expect(crawlingContext.session).toBeInstanceOf(Session);
            };

            const requestHandler = (crawlingContext: CheerioCrawlingContext) => {
                expect(crawlingContext === prepareCrawlingContext).toEqual(true);
                expect(crawlingContext.request).toBeInstanceOf(Request);
                expect(crawlingContext.session).toBeInstanceOf(Session);
                expect(typeof crawlingContext.$).toBe('function');
                expect(typeof crawlingContext.response).toBe('object');
                expect(typeof crawlingContext.contentType).toBe('object');

                throw new Error('some error');
            };

            const failedRequestHandler = (crawlingContext: Partial<CheerioCrawlingContext>, error: Error) => {
                expect(crawlingContext === prepareCrawlingContext).toEqual(true);
                expect(crawlingContext.request).toBeInstanceOf(Request);
                expect(crawlingContext.session).toBeInstanceOf(Session);
                expect(typeof crawlingContext.$).toBe('function');
                expect(typeof crawlingContext.response).toBe('object');
                expect(typeof crawlingContext.contentType).toBe('object');

                expect(error).toBeInstanceOf(Error);
                expect(error.message).toEqual('some error');
            };

            const cheerioCrawler = new CheerioCrawler({
                requestList,
                maxRequestRetries: 0,
                maxConcurrency: 1,

                preNavigationHooks: [preNavigationHook],
                requestHandler,
                failedRequestHandler,
            });
            await cheerioCrawler.run();
        });
    });

    test('should work with delete requests', async () => {
        const sources: Source[] = [1, 2, 3, 4].map((num) => {
            return {
                url: `${serverAddress}/special/mock?a=${num}`,
                method: 'DELETE',
            };
        });
        const requestList = await RequestList.open(null, sources);

        const failed: Request[] = [];

        const cheerioCrawler = new CheerioCrawler({
            requestList,
            maxConcurrency: 1,
            maxRequestRetries: 0,
            navigationTimeoutSecs: 5,
            requestHandlerTimeoutSecs: 5,
            requestHandler: async () => {},
            failedRequestHandler: async ({ request }) => {
                failed.push(request);
            },
        });

        await cheerioCrawler.run();

        expect(failed).toHaveLength(0);
    });

    test("enqueueLinks() should skip links that don't match the strategy post redirect", async () => {
        const succeeded: string[] = [];

        const crawler = new CheerioCrawler({
            maxConcurrency: 1,
            maxRequestRetries: 0,
            requestHandler: async ({ $, enqueueLinks }) => {
                succeeded.push($('title').text());
                await enqueueLinks({ strategy: EnqueueStrategy.SameOrigin });
            },
        });

        await crawler.run([`${serverAddress}/special/redirect`]);

        expect(succeeded).toHaveLength(1);
        expect(succeeded[0]).toEqual('Redirecting outside');
    });

    test('enqueueLinks should not log an enqueueLinks limit when only maxRequestsPerCrawl clamps', async () => {
        const crawler = new CheerioCrawler({
            maxRequestsPerCrawl: 1,
            requestHandler: async ({ enqueueLinks }) => {
                await enqueueLinks({ strategy: EnqueueStrategy.All });
            },
        });

        const infoSpy = vitest.spyOn(crawler.log, 'info');

        await crawler.run([`${serverAddress}/special/html-type`]);

        // The user passed no `limit`, so the skips must not be attributed to one
        expect(infoSpy).not.toHaveBeenCalledWith(expect.stringContaining('Skipping URLs in the handler'));
    });

    test('enqueueLinks should respect maxCrawlDepth', async () => {
        const succeeded: string[] = [];

        const crawler = new CheerioCrawler({
            maxCrawlDepth: 1,
            maxRequestsPerCrawl: 10, // to avoid accidental runaway
            requestHandler: async ({ $, enqueueLinks }) => {
                succeeded.push($('title').text());
                await enqueueLinks({ strategy: EnqueueStrategy.All });
            },
        });

        await crawler.run([`${serverAddress}/special/html-type`]);

        expect(succeeded).toHaveLength(2);
        expect(succeeded).toEqual(['Example Domain', 'Example Domains']);
    });
});