测试sequelize中的belongsTo属性

时间:2019-07-20 11:52:49

标签: javascript sequelize.js

我正在使用"sequelize": "^4.22.8"

我有两个模型:

Company.js

module.exports = (sequelize, DataTypes) => {
  const Company = sequelize.define('Company', {
    name: DataTypes.STRING,
    description: DataTypes.STRING,
  }, {})
  Company.associate = function(models) {
    Company.hasMany(models.Dividend)
  };
  return Company
};

Dividend.js

module.exports = (sequelize, DataTypes) => {
  const Dividend = sequelize.define('Dividend', {
    period: DataTypes.STRING,
    amount: DataTypes.FLOAT,
    yield: DataTypes.FLOAT,
  }, {})
  Dividend.associate = function(models) {
    Dividend.belongsTo(models.Company)
  }
  return Dividend
}

我的测试如下:

const chai = require('chai')
chai.use(require('chai-datetime'))
const assert = chai.assert

const models = require('../src/models')

const factories = require('./factories')
const truncate = require('./truncate')

describe('Dividend model', () => {
  let dividend

  beforeEach(async () => {
    // setup db
    await models.sequelize.sync()

    await truncate()

    // add 1 factory to the db
    dividend = await factories.factories.dividend()
  })

  it('should generate a dividend from the factory', async () => {
    assert.isOk(dividend.id)
  })

})

我通过以下方式创建工厂:

首先,我用index.js加载它们:

const { forEach } = require('lodash');
const requireDirectory = require('require-directory');

const factories = requireDirectory(module, './');

forEach(factories, (value, key) => { factories[key] = value.default; });

/* export default factories;
 */
module.exports = {
    factories
}

我的股息工厂如下所示:

const faker = require('faker');

const models = require('../../src/models');

const data = async (props = {}) => {
  const defaultProps = {   
    period: faker.random.arrayElement(['quarterly', 'monthly', 'yearly']),
    amount: faker.random.number(),
    yield: faker.random.number(),
  };

  return Object.assign({}, defaultProps, props);
};

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _default = async function _default() {
  var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  return models.Dividend.create((await data(props)));
};

exports.default = _default;

有人建议如何测试将company_id添加到工厂吗?

感谢您的答复!

0 个答案:

没有答案