question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to test with jest ?

See original GitHub issue

I have model method for method of controller. How to test it with jest ? How to create mock of Objection ?

const { Errors } = require('../../db/models/Errors');

module.exports = async function get(page = 0, perPage = 5, errorsFilter = {}) {
  try {
    const query = Errors
      .query()
      .orderBy('id', 'DESC')
      .page(page, perPage);

    // filter

    if (Object.keys(errorsFilter).length) {
      for (let field in errorsFilter) {
        if ( errorsFilter.hasOwnProperty(field) ) {
          if (field === 'dateStart') {
            query.where('date', '>=', `${ errorsFilter[field] }`);
          } else if (field === 'dateEnd') {
            query.where('date', '<=', `${ errorsFilter[field] }`);
          } else {
            query.where(field, 'like', `%${ errorsFilter[field] }%`);
          }
        }
      }
    }
    
    const { results, total } = await query;

    return {
      items:       results,
      itemsOnPage: Number(perPage),
      currentPage: Number(page),
      totalPage:   Math.ceil(total/perPage),
      totalItems:  Number(total)
    }
  } catch (error) {
    // log error -----------------------------------------------------------
    console.log({Error: error});
    // ---------------------------------------------------------------------
  }
};

My test file:

require('dotenv').config();

const express       = require('express');
const request       = require('supertest');
const bodyParser    = require('body-parser');
const { Objection } = require('objection');
const { QueryBuilder } = require('objection');
const { Errors }    = require('../../../../server/db/models/Errors');

const errors      = require('../../../../server/controllers/errors');
const { i18next, i18nextMiddleware } = require('../../../i18n-server');

const builder = QueryBuilder.forClass(Errors);

console.log(builder.resolve);

jest.spyOn(Errors, 'query').mockImplementation(builder.resolve({ type: 'test' }));

const app = express();

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.use(i18nextMiddleware);

app.get(
  '/',
  errors.getErrors
);

describe('get errors', () => {
  it('success', done => {
    i18next.on('initialized', () => {
      request(app)
        .get('/')
        .query({page: 1, perPage: 5})
        .end((err, res) => {
          if (err) return done(err);

          expect(res.status).toBe(200);

          done();
        });
    })
  });
});

I have error: TypeError: specificMockImpl.apply is not a function

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:16 (1 by maintainers)

github_iconTop GitHub Comments

7reactions
fiznoolcommented, Mar 23, 2020

I’m not sure if you should really be mocking out the database. I would consider any test that runs against Objection models to be an integration test, which should be backed by a real database.

If you really want to mock out the response, you could look at the resolve and reject Query Builder methods, although I’m unsure whether you can skip a database connection if using these.

As an aside, you might have more luck posting this sort of question on the gitter channel.

3reactions
otaviosoarescommented, Mar 20, 2020

I created this function, see if it helps

import { QueryBuilder } from 'objection'
export default function mockmodel(Model) {
  const query = QueryBuilder.forClass(Model)
  jest.spyOn(Model, 'query').mockReturnValue(query)
  return query
}
const body = { test : 1 }
const queryBuilderMock = mockModel(YourModel).resolve(body)
YourModel.query.insert({})
// if needed
const insertMock = jest.spyOn(queryBuilderMock, 'insert')
expect(insertMock).toHaveBeenCalledTimes(1)
Read more comments on GitHub >

github_iconTop Results From Across the Web

Jest · Delightful JavaScript Testing
Jest is a JavaScript testing framework designed to ensure correctness of any JavaScript codebase. It allows you to write tests with an approachable, ......
Read more >
Jest Tutorial for Beginners: Getting Started With JavaScript ...
Time to create your first Jest test. Open up filterByTerm.spec.js and create a test block: describe("Filter function" ...
Read more >
Jest Testing Tutorial: 5 Easy Steps - Testim Blog
1. Install Jest Globally · 2. Create a Sample Project · 3. Add Jest to the Project · 4. Write Your First Test...
Read more >
Jest Tutorial - JavaScript Unit Testing Using Jest Framework
Jest is a Javascript Testing framework built by Facebook. It is primarily designed for React (which is also built by Facebook) based apps...
Read more >
Jest Crash Course - Learn How to Test your JavaScript ...
In this crash course, we will cover Jest which is a terrific JavaScript testing frameworkSecond ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found