Thursday, 3 January 2019

JestJS: Async test isn't stopped

I got two problems with this jest test:

  1. Is it possible to define the Content collection only once instead of doing that inside of the test?
  2. I do get this error:

    Jest did not exit one second after the test run has completed. This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with --detectOpenHandles to troubleshoot this issue.

I don't see why my async code weren't stopped...

import resolvers from 'resolvers/'
import Db from 'lib/db'
const db = new Db()

describe('Resolver', () => {
  let token

  beforeAll(async () => {
    await db.connect()
  })
  beforeEach(async () => {
    token = 'string'
    await db.dropDB()
  })

  describe('articleGetContent()', () => {
    test('should return dataset', async () => {
      // SETUP
      const Content = db.connection.collection('content')
      const docs = [{
        // some content...
      }]
      await Content.insertMany(docs)
      // EXECUTE
      const result = await resolvers.Query.articleGetContent({}, {
        id: '123,
        language: 'en'
      }, {
        token
      })
      // VERIFY
      expect(result).toBeDefined()
    })
  })
})

resolver

import { articleGetContent } from '../models/article'

export default {
  Query: {
    articleGetContent: async (obj, { id }, { token }) => articleGetContent(id, token)
  }
}


This is how my db class looks like

db.js

export default class Db {
  constructor (uri, callback) {
    const mongo = process.env.MONGO || 'mongodb://localhost:27017'
    this.mongodb = process.env.MONGO_DB || 'testing'
    this.gfs = null
    this.connection = MongoClient.connect(mongo, { useNewUrlParser: true })
    this.connected = false
    return this
  }

  async connect (msg) {
    if (!this.connected) {
      try {
        this.connection = await this.connection
        this.connection = this.connection.db(this.mongodb)
        this.gfs = new mongo.GridFSBucket(this.connection)
        this.connected = true
      } catch (err) {
        console.error('mongo connection error', err)
      }
    }
    return this
  }
}



from JestJS: Async test isn't stopped

No comments:

Post a Comment