I am new to node and I am just attempting at writing a simple backend blog API. I am using bookshelf.js as the ORM and I am attempting to use bookshelf-validate in order to enforce requirements on an Article model that I made. The validations I have included with the Article model are merely the isRequired validations on all fields (fields being title, author, and body). One of my tests creates a new article with all the fields defined and the test is failing. Here is my code,
//here is the bookshelf model
const Bookshelf = require('../config/bookshelf.config');
const Article = Bookshelf.Model.extend({
tableName: 'articles',
hasTimestamps: true,
validations: {
title: {
isRequired: true
},
author: {
isRequired: true
},
body: {
isRequired: true
}
}
});
module.exports = Bookshelf.model('Article', Article);
//test file below
process.env.NODE_ENV = 'test';
const chaiAsPromised = require('chai-as-promised');
const { expect, assert } = require('chai').use(chaiAsPromised);
const knex = require('knex')(require('../knexfile')[process.env.NODE_ENV]);
const Article = require('../models/article');
describe('Articles', function () {
beforeEach(function () {
return knex.migrate.rollback()
.then(function () {
return knex.migrate.latest();
});
});
after(function () {
return knex.migrate.rollback();
});
describe('test db', function () {
it('should not have any models at start of test suite', function () {
Article.forge().fetch().then(function (results) {
expect(results).to.equal(null);
});
});
it('should save a model to the db', function () {
const article = new Article({
title: 'first blog',
author: 'john doe',
body: 'blah blah'
}).save();
return expect(article).to.be.fulfilled;
});
});
});
Here is the gist as well https://gist.github.com/Euklidian-Space/bf10fd1a72bec9190867854d1ea309d9
Thanks in advance.
Your
should save a model to the dbtest is not taking asynchronicity into account. It may save the entry but theexpect()call may come too early to get the fulfilled promise.So replace
by something like