Testing Promises in Jest

I have finally found a decent pattern to test promises.

You can mock a service to return Promise.resolve(x) or Promise.reject(“reason”).

Sample is from contentful-to-neo4j

test(“If contentful is empty then nothing is sent to the db”, (done) => {
  const contentfulService=mockContentfulServiceFactory();
  const neo4jService=mockNeo4jServiceFactory();
  const log=mockLogFactory();
  const systemService=mockSystemServiceFactory();
  contentfulService.getAssets.mockReturnValue(     Promise.resolve(contentfulService.emptyResult));
 contentfulService.getEntries.mockReturnValue(     Promise.resolve(contentfulService.emptyResult));
 const transformService=transformServiceFactory(contentfulService, neo4jService,   contentfulBatchSize, log, systemService);
  setTimeout( () => {

The trick is to use setTimeout of 1 to happen after the promises have been resolved.
Since the promises are already complete they all resolve before the next millisecond. The done holds the test up for the timeout.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s