How to test with jest ?
See original GitHub issueI 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:
- Created 4 years ago
- Comments:16 (1 by maintainers)
Top 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 >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
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.
I created this function, see if it helps