使用bookshelf.js和bookshelf-validate进行测试失败

时间:2017-01-01 01:02:10

标签: promise mocha bookshelf.js

我是node的新手,我只是在尝试编写一个简单的后端博客API。我使用bookshelf.js作为ORM,我正在尝试使用bookshelf-validate来强制执行我制作的文章模型的要求。我在Article模型中包含的验证仅仅是所有字段的isRequired验证(字段是标题,作者和正文)。我的一个测试创建了一篇新文章,其中定义了所有字段,测试失败。这是我的代码,

//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;
    });
  });
});

这也是要点https://gist.github.com/Euklidian-Space/bf10fd1a72bec9190867854d1ea309d9

提前致谢。

1 个答案:

答案 0 :(得分:0)

您的should save a model to the db测试未考虑异步性。它可以保存条目,但expect()电话可能来得太早,无法实现履行承诺。

所以替换

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;
});

类似

it('should save a model to the db', function (done) {
  const article = new Article({
    title: 'first blog',
    author: 'john doe',
    body: 'blah blah'
  })
  .save()
  .then(function () { done() })
  .catch(function (err) { done(err) });
});