我正在尝试使用带有sequelize的mocha来设置测试。我想在每次测试之前和之后截断所有表并创建新表。我以为我可以使用sequelize.sync
。
这是我的测试:
import chai from "chai";
import assert from "assert";
import app from "../../src/app";
import chaiHttp from "chai-http";
import factories from "../factories";
import Sequelize from "sequelize";
// import dotenv from "dotenv";
// dotenv.config({path: ".env.test"});
chai.use(chaiHttp);
describe("'regions'service", () => {
beforeEach(async () => {
await Sequelize.sync({ force: true });
});
it("should POST area", async () => {
const region = await factories.create("region");
const dummy = {
name: "New area",
open: true,
description: "This is a cool area!",
gps: "122.123, 123.4123",
regionId: region.dataValues.id
};
const res = await chai
.request(app)
.post("/api/areas")
.send(dummy);
assert.equal(res.body.name, dummy.name);
});
});
我的错误讯息:
TypeError: _sequelize2.default.sync is not a function
答案 0 :(得分:0)
我想我明白了所有错误的续集。我每次尝试使用时都必须使用sequelize来建立连接。
所以将文件更改为:
import chai from "chai";
import assert from "assert";
import app from "../../src/app";
import chaiHttp from "chai-http";
import factories from "../factories";
import db from "../../src/models";
// import dotenv from "dotenv";
// dotenv.config({path: ".env.test"});
chai.use(chaiHttp);
describe("'regions'service", () => {
beforeEach(async () => {
await db.sequelize.sync({ force: true, logging: false });
});
it("should POST area", async () => {
const region = await factories.create("region");
const dummy = {
name: "New area",
open: true,
description: "This is a cool area!",
gps: "122.123, 123.4123",
regionId: region.dataValues.id
};
const res = await chai
.request(app)
.post("/api/areas")
.send(dummy);
assert.equal(res.body.name, dummy.name);
});
});
我的db文件如下所示:
"use strict";
const fs = require("fs");
const path = require("path");
const Sequelize = require("sequelize");
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || "development";
const config = require(__dirname + "/../config/config.json")[env];
const db = {};
let sequelize;
if (config.use_env_variable) {
sequelize = new Sequelize(process.env[config.use_env_variable]);
} else {
sequelize = new Sequelize(
config.database,
config.username,
config.password,
config
);
}
fs
.readdirSync(__dirname)
.filter(file => {
return (
file.indexOf(".") !== 0 && file !== basename && file.slice(-3) === ".js"
);
})
.forEach(file => {
var model = sequelize["import"](path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;