简体   繁体   中英

Test async function with jest

I'm trying to mock the database connection object in order to do my tests but the error im getting is always the same.

I already tried with another solutions but the mock is always returning me the same object. After a little reaserch and changes I found another solution like this

// connection.js
/* istanbul ignore file */
const mysql = require('mysql');

let pool;
const config = require('./config.js');

const connection = getPool();
/**
 * Singleton pool connection
 * @return {Pool} the pool connection
 */
function getPool() {
  if (pool) {
    return pool;
  }
  pool = mysql.createPool(config);
  return pool;
}

module.exports = connection;
// database.js
const connection = require('./connection')
function find() {
  return new Promise((resolve, reject) => {
    const query = 'select * from table`;
    connection.query(query, (err, res) => {
      if (err) {
        reject(new DatabaseError('Error'));
      }
      resolve(res);
    });
  });
}

and finally my test file looks like this


const database = require('./database.js');
const connection = require('./connection.js');
const { expect } = chai;
const DatabaseError = require('../../../src/errors/DatabaseError');

jest.mock('./connection.js');
  describe('testing find all', () => {
    test('testing error ', async () => {
      connection.query.mockImplementation(() => (q,  cb) => cb(res, null, null));
      try {
        await database.find();
      } catch (e) {
      expect(err).to.be.an.instanceof(DatabaseError);
      }
    });
  });

The error im getting is always the same

    : Timeout - Async callback was not invoked within the 10000ms timeout specified by jest.setTimeout.Timeout - Async callback was not invoked within the 10000ms timeout specified by jest.setTimeout.Error:

      11 |   describe('test find all', () => {
    > 12 |     test('testing error ', async () => {

I already tried using return statement and async done but nothing resolves this problem

any help?

The reason that I'm using mockimplementation is because i need to change every test that query value

You should mock the implementation of connection.query method like this:

connection.query.mockImplementation((q, cb) => cb(mError, null));

See the difference? You mock it as a high order function. It's not correct. Here is a working example:

connection.js :

/* istanbul ignore file */
const mysql = require('mysql');

let pool;
const config = require('./config.js');

const connection = getPool();
/**
 * Singleton pool connection
 * @return {Pool} the pool connection
 */
function getPool() {
  if (pool) {
    return pool;
  }
  pool = mysql.createPool(config);
  return pool;
}

module.exports = connection;

database.js :

const connection = require('./connection');

function find() {
  return new Promise((resolve, reject) => {
    const query = 'select * from table';
    connection.query(query, (err, res) => {
      if (err) {
        return reject(new Error('Error'));
      }
      resolve(res);
    });
  });
}

module.exports = { find };

config.js :

module.exports = {};

database.test.js :

const database = require('./database.js');
const connection = require('./connection.js');

jest.mock('./connection.js');

describe('testing find all', () => {
  test('testing error ', async () => {
    const mError = new Error('network');
    connection.query.mockImplementation((q, cb) => cb(mError, null));
    try {
      await database.find();
    } catch (e) {
      expect(e).toBeInstanceOf(Error);
    }
  });
});

unit test results with coverage report:

 PASS  stackoverflow/61261886/database.test.js (10.531s)
  testing find all
    ✓ testing error  (5ms)

-------------|---------|----------|---------|---------|-------------------
File         | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-------------|---------|----------|---------|---------|-------------------
All files    |   88.89 |       50 |     100 |   88.89 |                   
 config.js   |     100 |      100 |     100 |     100 |                   
 database.js |    87.5 |       50 |     100 |    87.5 | 10                
-------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        12.222s

source code: https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/61261886

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM