单元测试BelongsToMany在Sequelize中使用Jasmine

时间:2017-05-23 03:37:32

标签: javascript node.js unit-testing sequelize.js has-and-belongs-to-many

我正在使用Node和Sequelize(使用Yeoman angular-fullstack生成器)构建一个简单的博客样式应用程序。我正在尝试为我的文章模型写出一些测试,但我无法找出构建测试的正确方法。文章和用户通过双向belongsToMany关系连接。

我能够验证我的对象存在setter和getter方法,但无法验证它们是否有效。我正在努力工作的代码是在文件末尾注释掉的代码。我很感激帮助让单元测试正常工作,谢谢!

'use strict';

/* globals describe, expect, it, beforeEach, afterEach */

var app = require('../..');
import request from 'supertest';
import {User, Article} from '../../sqldb';

var user = [];
var article = [];

var genArticles = function(i) {
  for(var i = 0; i < 3; i++) {
    article[i] = genArticle(i);
  }
  return article;
}

var genUsers = function(i) {
  for(var i = 0; i < 3; i++) {
    user[i] = genUser(i);
  }
  return user;
}

var genUser = function(i) {
  return User.build({
    provider: 'local',
    name: `Fake User ${i}`,
    email: `test${i}@example.com`,
    password: 'password'
  });
};

var genArticle = function(i) {
  return Article.build({
    title: `Fake Article ${i}`,
    body: `test${i}`
  });
};

describe("Article-User relations", function() {
  before(function() {
    return User.sync().then(function() {
      return User.destroy({ where: {} }).then(function() {
        return Article.sync().then(function() {
          return Article.destroy({ where: {} }).then(function() {
          });
        });
      });
    });
  });

  beforeEach(function(done) {
    genArticles();
    genUsers();
    done();
  });

  afterEach(function() {
    return User.sync().then(function() {
      return User.destroy({ where: {} }).then(function() {
        return Article.sync().then(function() {
          return Article.destroy({ where: {} }).then(function() {
          });
        });
      });
    });
  });

  it('should begin with no data', function() {
    expect(User.findAll()).to
      .eventually.have.length(0);
    return expect(Article.findAll()).to
      .eventually.have.length(0);
  });


  describe("Check methods exist and", function(done) {
    before(function(done) {
      article.forEach((a) =>  {a.save()});
      user.forEach((a) =>  {a.save()});
      done();
    });
    it("should have setter methods", function() {
      expect(typeof article[0].setUsers).to.equal("function");
      expect(typeof user[0].setArticles).to.equal("function");
    });
    it("should have getter methods", function() {
      expect(typeof article[0].getUsers).to.equal("function");
      expect(typeof user[0].getArticles).to.equal("function");
    });

    /* THIS IS THE TEST THAT ISN'T WORKING */

    /*
    it("setter and getter methods for article objects should work", function() {
      return article[0].setUsers(user).then(() => {
        return article[0].hasUsers(user).then( result => { 
          expect(result).should.eventually.equal.true;
        })
      }).catch( e => { console.log(e) });
      //expect(typeof user[0].setArticles).to.equal("function");
    });
    */

  });
});

0 个答案:

没有答案