graphile / graphile/worker

Worker Test Example

Open
#126 7 comments 2 reactions 0 assignees View on GitHub
Dominant language
TypeScript
Stars
2.4k
Forks
126
Avg merge
2d 2h
Merged PRs (30d)
9

Description

Was looking through the code for how to test as its not really clear from the readme. Here is something I hacked up.

Would appreciate any feedback on it. Once its decent I would be happy to make a pr. This example is for jest with @babel/preset-env

Thanks for the great lib!

``` javascript
// tasks/hello.js
export default async (payload, helpers) => {
const { name } = payload;
helpers.logger.info(`Hello, ${name}`);
};
```

``` javascript
// test/tasks/hello.test.js
import hello from '../../src/tasks/hello';
import config from 'config'; //
import { runOnce, quickAddJob } from 'graphile-worker';

const connectionString = config.get('pg_db_url'); // i.e. "postgres://user:pass@host:port/db?ssl=true"
const payloadName = 'Bobby Tables';

// based on https://github.com/graphile/worker#quickstart-library
describe('hello task', () => {
it('does things', async (done) => {
const spy = jest.spyOn(global.console, 'info');
// Or add a job to be executed:
const job = await quickAddJob(
// makeWorkerUtils options
{ connectionString },

// Task identifier
'hello',

// Payload
{ name: payloadName }
);

console.log(job);
expect(job).toBeTruthy();

// Run a worker to execute jobs:
// eslint-disable-next-line
const runner = await runOnce({
connectionString,
concurrency: 5,
// Install signal handlers for graceful shutdown on SIGINT, SIGTERM, etc
noHandleSignals: false,
pollInterval: 1000,
// you can set the taskList or taskDirectory but not both
taskList: {
hello,
},
// or:
// taskDirectory: `${__dirname}/tasks`,
});

// until https://github.com/graphile/worker/issues/28 is resolved with events
// or i write my own event emmitter. we'll just test the logger
//
// this also is ok https://github.com/bpedersen/jest-mock-console
// but i don't want to swallow logs this early in teh dev cycle
//
// https://stackoverflow.com/a/56677834/511710
// https://jest-bot.github.io/jest/docs/expect.html#expectstringcontainingstring

/**
* graphile-worker's build in logger passes console calls like this
*
* 1: "[%s%s] %s: %s", "job", "(worker-e03827077c435f77f5: hello{15})", "INFO", "Hello, Bobby Tables"
* 2: "[%s%s] %s: %s", "worker", "(worker-e03827077c435f77f5)", "INFO", "Completed task 15 (hello) with success (20.03ms)"
*
*/
expect(spy).toHaveBeenCalledWith(
expect.anything(),
expect.anything(),
expect.anything(),
expect.anything(),
expect.stringContaining(payloadName)
);

done();
});
});

```

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.