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.
TypeScript apifyautomationcrawlercrawlingheadlessheadless-chromejavascriptnodejsnpmplaywrightpuppeteerscraperscrapingtypescriptweb-crawlerweb-crawlingweb-scraping
Improved unit tests for Apifier.main(), better handling of GET requests
Jan Curn0383d1f12456
diff --git a/README.md b/README.mdindex 780ad2f8a..f08124ac7 100644--- a/README.md+++ b/README.md@@ -49,10 +49,11 @@ The user function has a single argument `options` which is an object such as:```javascript{input: {- // HTTP payload body parsed using body-parser middleware:+ // HTTP request body parsed using body-parser middleware:// * For 'application/json' content type the body is parsed from JSON to any JavaScript object// * For 'text/*' content types the body is passed as String// * For any other content type the body is passed as raw Buffer object+ // For HTTP GET request, body is null.body: Object|String|Buffer,// HTTP method used to pass the datadiff --git a/build/actor.js b/build/actor.jsindex c7cb3def4..6acb01401 100644--- a/build/actor.js+++ b/build/actor.js@@ -35,7 +35,7 @@ var main = exports.main = function main(userFunc) {var handler = function handler(req, res) {var options = {input: {- body: req.body,+ body: req.method === 'GET' ? null : req.body,method: req.method,contentType: req.headers['content-type']}@@ -46,27 +46,32 @@ var main = exports.main = function main(userFunc) {}).then(function () {res.statusCode = 200;}).catch(function (err) {- console.log('User act failed: ' + err);+ console.error('Main function ended with exception:');+ console.error(err.stack || err);res.statusCode = 500;}).then(function () {res.end(function (err) {if (err) {console.log('Failed to send HTTP response: ' + err);+ process.exit(2);+ }+ if (res.statusCode === 500) {process.exit(1);+ } else {+ console.log('Main function ended successfully');+ process.exit(0);}- console.log('All good, finishing the act');- process.exit(0);});}).catch(function (err) {console.log('Something went terribly wrong: ' + err);- process.exit(2);+ process.exit(3);});};var app = (0, _express2.default)();// parse JSON, pass texts and raw data- app.use(_bodyParser2.default.json());+ app.use(_bodyParser2.default.json({ type: '*/json' }));app.use(_bodyParser2.default.text({ type: 'text/*' }));app.use(_bodyParser2.default.raw({ type: '*/*' }));app.use(handler);diff --git a/build/utils.js b/build/utils.jsindex 12916f37a..978968c84 100644--- a/build/utils.js+++ b/build/utils.js@@ -7,6 +7,9 @@ Object.defineProperty(exports, "__esModule", {var promisesDependency = typeof Promise === 'function' ? Promise : null;+// TODO: add methods to override console.log() and console.error(), add unit tests for that!++/*** Sets the promise dependency the SDK will use wherever Promises are returned.* Passing `null` will force the SDK to use native Promises if they are available.diff --git a/package.json b/package.jsonindex 3d501cc05..a8867a3cc 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "apifier",- "version": "0.0.20",+ "version": "0.0.21","description": "Apifier SDK for JavaScript","main": "build/index.js","keywords": [diff --git a/src/actor.js b/src/actor.jsindex f1eb8da3e..6a871fd22 100644--- a/src/actor.js+++ b/src/actor.js@@ -18,7 +18,7 @@ export const main = (userFunc) => {const handler = (req, res) => {const options = {input: {- body: req.body,+ body: req.method === 'GET' ? null : req.body,method: req.method,contentType: req.headers['content-type'],},@@ -32,29 +32,34 @@ export const main = (userFunc) => {res.statusCode = 200;}).catch((err) => {- console.log(`User act failed: ${err}`);+ console.error('Main function ended with exception:');+ console.error(err.stack || err);res.statusCode = 500;}).then(() => {res.end((err) => {if (err) {console.log(`Failed to send HTTP response: ${err}`);+ process.exit(2);+ }+ if (res.statusCode === 500) {process.exit(1);+ } else {+ console.log('Main function ended successfully');+ process.exit(0);}- console.log('All good, finishing the act');- process.exit(0);});}).catch((err) => {console.log(`Something went terribly wrong: ${err}`);- process.exit(2);+ process.exit(3);});};const app = express();// parse JSON, pass texts and raw data- app.use(bodyParser.json());+ app.use(bodyParser.json({ type: '*/json' }));app.use(bodyParser.text({ type: 'text/*' }));app.use(bodyParser.raw({ type: '*/*' }));app.use(handler);diff --git a/src/utils.js b/src/utils.jsindex 5d2fe871a..750334152 100644--- a/src/utils.js+++ b/src/utils.js@@ -2,6 +2,8 @@let promisesDependency = typeof Promise === 'function' ? Promise : null;+// TODO: add methods to override console.log() and console.error(), add unit tests for that!+/*** Sets the promise dependency the SDK will use wherever Promises are returned.diff --git a/test/actor.js b/test/actor.jsindex fce01c3fb..b47a37bd0 100644--- a/test/actor.js+++ b/test/actor.js@@ -4,6 +4,8 @@ import tmp from 'tmp';import request from 'request';import portastic from 'portastic';+// TODO: override console.log() to test the error messages (now they are printed to console)+// NOTE: use require() here because this is how its done in actsconst Apifier = process.env.TEST_BABEL_BUILD ? require('../build/index') : require('../src/index');@@ -11,19 +13,8 @@ if (process.env.TEST_BABEL_BUILD) console.log('Running with TEST_BABEL_BUILD opt/* global process */--const processExitOverride = (code) => {- // TODO: the codes should be tested- console.log(`Exit with code: ${code}`);-};--const origProcessExit = process.exit;-let freePorts = [];before(() => {- // intercept calls to process.exit()- process.exit = processExitOverride;-// find free ports for testingreturn portastic.find({min: 50000,@@ -34,12 +25,13 @@ before(() => {});});+// always restore original process.exit()+const origProcessExit = process.exit;after(() => {- // restore process.exit()process.exit = origProcessExit;});-const getFreePort = () => freePorts.pop();+const popFreePort = () => freePorts.pop();const createWatchFile = () => {@@ -52,52 +44,87 @@ const createWatchFile = () => {return path;};-const testWatchFileEmpty = (path) => {+const testWatchFileWillBecomeEmpty = (path, waitMillis) => {+ const startedAt = Date.now();return new Promise((resolve, reject) => {- setTimeout(() => {+ const intervalId = setInterval(() => {const stat = fs.statSync(path);if (stat.size !== 0) {- reject('Watch file not written');+ if (Date.now() - startedAt >= waitMillis) reject(`Watch file not written in ${waitMillis} millis`);} else {+ clearInterval(intervalId);resolve();}- }, 100);+ }, 20);});};-const testRequestToMain = (method, bodyRaw, contentType) => {- const port = getFreePort();+const testMain = (method, bodyRaw, contentType, userFunc, expectedExitCode = 0) => {+ const port = popFreePort();process.env.APIFIER_INTERNAL_PORT = port;+ process.env.APIFIER_WATCH_FILE = createWatchFile();- return new Promise((resolve, reject) => {- const req = {- url: `http://127.0.0.1:${port}/`,- method,- body: bodyRaw,- headers: {- 'Content-Type': contentType,- },- timeout: 1000,- };+ // intercept calls to process.exit()+ const EMPTY_EXIT_CODE = 'dummy';+ let exitCode = EMPTY_EXIT_CODE;+ process.exit = (code) => {+ exitCode = code;+ };+ return new Promise((resolve, reject) => {let expectedBody = bodyRaw;if (contentType === 'application/json') expectedBody = JSON.parse(bodyRaw);- request(req, (err) => {- if (err) return reject(err);- });+ // give server a little time to start listening before sending the request+ setTimeout(() => {+ const req = {+ url: `http://127.0.0.1:${port}/`,+ method,+ body: bodyRaw,+ headers: {},+ timeout: 1000,+ };+ if (contentType) req.headers['Content-Type'] = contentType;++ request(req, (err) => {+ if (err) return reject(err);+ });+ }, 20);Apifier.main((opts) => {// console.dir(opts);try {expect(opts.input.method).to.equal(method);- expect(opts.input.contentType).to.equal(contentType);+ if (contentType) expect(opts.input.contentType).to.equal(contentType);expect(opts.input.body).to.deep.equal(expectedBody);+ resolve();} catch (err) {reject(err);}- resolve();+ // call user func to test other behavior+ if (userFunc) userFunc(opts);+ });+ })+ .then(() => {+ // watch file should be empty by now+ return testWatchFileWillBecomeEmpty(process.env.APIFIER_WATCH_FILE, 0);+ })+ .then(() => {+ // test process exit code is as expected+ return new Promise((resolve, reject) => {+ const intervalId = setInterval(() => {+ if (exitCode === EMPTY_EXIT_CODE) return;+ clearInterval(intervalId);+ // restore process.exit()+ process.exit = origProcessExit;+ try {+ expect(exitCode).to.equal(expectedExitCode);+ resolve();+ } catch (err) {+ reject(err);+ }+ }, 20);});});};@@ -129,23 +156,31 @@ describe('Apifier.main()', () => {expect(fn).to.throw(Error);});- it('truncates watch file', () => {- process.env.APIFIER_WATCH_FILE = createWatchFile();- process.env.APIFIER_INTERNAL_PORT = getFreePort();- Apifier.main(() => {});- return testWatchFileEmpty(process.env.APIFIER_WATCH_FILE);+ it('passes text/plain POST request', () => {+ return testMain('POST', 'testxxx', 'text/plain');+ });++ it('passes application/json PUT request', () => {+ return testMain('PUT', JSON.stringify({ abc: 123 }), 'application/json');});- it('passes text/plain request', () => {- return testRequestToMain('POST', 'testxxx', 'text/plain');+ it('passes raw POST request', () => {+ return testMain('POST', new Buffer('somebinarydata'), 'image/png');});- it('passes application/json request', () => {- return testRequestToMain('PUT', JSON.stringify({ abc: 123 }), 'application/json');+ it('passes empty GET request with application/json content type', () => {+ return testMain('GET', null, 'application/json');});- it('passes raw request', () => {- return testRequestToMain('PUT', new Buffer('somebinarydata'), 'image/png');+ it('passes empty GET request with no content type', () => {+ return testMain('GET', null, null);+ });++ it('on exception exits process with code 1', () => {+ const userFunc = () => {+ throw new Error('Test exception');+ };+ return testMain('PUT', 'testxxx', 'text/plain', userFunc, 1);});// TODO: test responses from act, exceptions etc. !@@ -156,6 +191,6 @@ describe('Apifier.heyIAmReady()', () => {it('it works as expected', () => {process.env.APIFIER_WATCH_FILE = createWatchFile();Apifier.heyIAmReady();- return testWatchFileEmpty(process.env.APIFIER_WATCH_FILE);+ return testWatchFileWillBecomeEmpty(process.env.APIFIER_WATCH_FILE, 1000);});});