Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion tests/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ Common to every type's serialization:

### Public API contract

`tests/unit/public-api.test.js` — 7 tests guarding the `exports` map from [package.json](../package.json):
`tests/unit/public-api.test.js` — 10 tests guarding the `exports` map from [package.json](../package.json):

```json
"exports": {
Expand All @@ -166,6 +166,9 @@ Every other test already imports the package by name, so a broken main entry wou
| `"@captcha-solver-api/javascript-sdk/exceptions" exposes every error class` | the `./exceptions` subpath resolves and hands back every class |
| `subpaths and the main entry expose the same classes` | these are the **same** objects, not duplicate module instances — otherwise `instanceof` would break for anyone mixing import styles |
| `internal modules are not reachable as subpaths` | `@captcha-solver-api/javascript-sdk/client` is rejected: the file exists, but it is not declared in `exports` and must stay private |
| `main entry exposes the same API as the ESM build` | `require()` of `.` loads `index.cjs` and exposes the same names as the ESM build |
| `"./tasks" and "./exceptions" subpaths expose every class` | the `require` variants of both subpaths resolve and hand back every class |
| `the CJS client and tasks are functional` | the CJS build actually works: client validation and task serialization |

The class lists in the test are spelled out as explicit arrays rather than derived from the module itself. That is deliberate: comparing an export against itself always passes and checks nothing. Adding a new captcha type means extending the array by hand — and that is exactly the point where the decision to make a class public gets recorded explicitly.

Expand Down
91 changes: 91 additions & 0 deletions tests/unit/async/client.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -265,3 +265,94 @@ describe('CaptchaClient (async)', () => {
await expect(client.createTask(task)).rejects.toThrow(NetworkError);
});
});

describe('CaptchaClient error edge cases (async)', () => {
let client;

const task = () => new Tasks.RecaptchaV2Proxyless({
websiteURL: 'https://example.com',
websiteKey: 'test_key'
});

const respond = (body) => jest.fn(() => Promise.resolve({
ok: true,
json: () => Promise.resolve(body)
}));

beforeEach(() => {
client = new CaptchaClient({
clientKey: 'test_key',
timeout: 5000,
pollingInterval: 10
});
});

test('throws NetworkError on a non-2xx HTTP status without reading the body', async () => {
const json = jest.fn();
global.fetch = jest.fn(() => Promise.resolve({
ok: false,
status: 502,
statusText: 'Bad Gateway',
json
}));

const error = await client.createTask(task()).catch((e) => e);
expect(error).toBeInstanceOf(NetworkError);
expect(error.message).toBe('HTTP error: 502 Bad Gateway');
expect(json).not.toHaveBeenCalled();
});

test('throws NetworkError when the response body is not valid JSON', async () => {
const parseError = new SyntaxError('Unexpected token < in JSON at position 0');
global.fetch = jest.fn(() => Promise.resolve({
ok: true,
json: () => Promise.reject(parseError)
}));

const error = await client.getBalance().catch((e) => e);
expect(error).toBeInstanceOf(NetworkError);
expect(error).not.toBeInstanceOf(ApiError);
expect(error.message).toBe(parseError.message);
expect(error.originalError).toBe(parseError);
});

test('wraps a non-Error rejection into NetworkError', async () => {
global.fetch = jest.fn(() => Promise.reject('connection reset'));

const error = await client.getBalance().catch((e) => e);
expect(error).toBeInstanceOf(NetworkError);
expect(error.message).toBe('connection reset');
expect(error.originalError).toBe('connection reset');
});

test('ApiError falls back to UNKNOWN_ERROR when the API sends no details', async () => {
global.fetch = respond({ errorId: 1 });

const error = await client.createTask(task()).catch((e) => e);
expect(error).toBeInstanceOf(ApiError);
expect(error.errorCode).toBe('UNKNOWN_ERROR');
expect(error.errorDescription).toBe('Unknown API error');
});

test('ApiError uses the "error" field when errorDescription is absent', async () => {
global.fetch = respond({ errorId: 1, errorCode: 'ERROR_ZERO_BALANCE', error: 'No funds' });

const error = await client.createTask(task()).catch((e) => e);
expect(error).toBeInstanceOf(ApiError);
expect(error.errorCode).toBe('ERROR_ZERO_BALANCE');
expect(error.errorDescription).toBe('No funds');
});

test('solve returns an empty object when a ready result has no solution', async () => {
let callCount = 0;
global.fetch = jest.fn(() => {
callCount++;
const body = callCount === 1
? { errorId: 0, taskId: 12345 }
: { errorId: 0, status: 'ready' };
return Promise.resolve({ ok: true, json: () => Promise.resolve(body) });
});

await expect(client.solve(task())).resolves.toEqual({});
});
});
37 changes: 37 additions & 0 deletions tests/unit/public-api.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
*/

import fs from 'node:fs';
import { createRequire } from 'node:module';

import * as pkg from '@captcha-solver-api/javascript-sdk';
import * as tasksEntry from '@captcha-solver-api/javascript-sdk/tasks';
Expand Down Expand Up @@ -98,3 +99,39 @@ describe('module privacy', () => {
await expect(import('@captcha-solver-api/javascript-sdk/client')).rejects.toThrow();
});
});

describe('CommonJS build (require)', () => {
// Every other test imports the ESM build. These guard the .cjs files that
// "require" consumers get through the "exports" map.
const require = createRequire(import.meta.url);

test('main entry exposes the same API as the ESM build', () => {
const cjs = require('@captcha-solver-api/javascript-sdk');

expect(Object.keys(cjs).sort()).toEqual(Object.keys(pkg).sort());
expect(Object.keys(cjs.Tasks).sort()).toEqual(Object.keys(pkg.Tasks).sort());
expect(cjs.__version__).toBe(pkg.__version__);
});

test('"./tasks" and "./exceptions" subpaths expose every class', () => {
const cjsTasks = require('@captcha-solver-api/javascript-sdk/tasks');
const cjsExceptions = require('@captcha-solver-api/javascript-sdk/exceptions');

for (const name of TASK_CLASSES) {
expect(typeof cjsTasks[name]).toBe('function');
}
for (const name of ERROR_CLASSES) {
expect(typeof cjsExceptions[name]).toBe('function');
}
});

test('the CJS client and tasks are functional', () => {
const { CaptchaClient, Tasks, ValidationError } = require('@captcha-solver-api/javascript-sdk');

expect(() => new CaptchaClient({})).toThrow(ValidationError);
expect(new Tasks.ImageToText({ body: 'base64' }).toDict()).toEqual({
type: 'ImageToTextTask',
body: 'base64'
});
});
});
7 changes: 6 additions & 1 deletion tests/unit/task-validation.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,12 @@ describe('built-in task validation', () => {
['CoordinatesTask', { body: ' ' }, 'body'],
['YandexSmartCaptchaImageTask', {}, 'image, imgInstructions'],
['YandexSmartCaptchaImageTask', { image: 'image', imgInstructions: '' }, 'imgInstructions'],
['TencentTaskProxyless', { websiteURL: 'https://example.com' }, 'appId']
['TencentTaskProxyless', { websiteURL: 'https://example.com' }, 'appId'],
['RecaptchaV2Enterprise', { websiteURL: 'https://example.com', websiteKey: 'key' }, 'proxyType, proxyAddress, proxyPort'],
['Turnstile', { websiteURL: 'https://example.com', websiteKey: 'key', proxyType: 'http' }, 'proxyAddress, proxyPort'],
['GeeTest', { websiteURL: 'https://example.com', gt: 'gt', challenge: 'challenge', proxyType: 'http', proxyAddress: '127.0.0.1' }, 'proxyPort'],
['YandexSmartCaptchaTask', { websiteURL: 'https://example.com', websiteKey: 'key' }, 'proxyType, proxyAddress, proxyPort'],
['TencentTask', { websiteURL: 'https://example.com', appId: 'app' }, 'proxyType, proxyAddress, proxyPort']
])('%s reports missing required parameters', (className, params, expected) => {
expect(() => new Tasks[className](params)).toThrow(ValidationError);
expect(() => new Tasks[className](params)).toThrow(expected);
Expand Down
Loading