gpt4 book ai didi

mocha.js - Sequelize 同步不是一个功能

转载 作者:行者123 更新时间:2023-12-03 22:22:12 24 4
gpt4 key购买 nike

我正在尝试使用带有 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

最佳答案

我想我理解 sequelize 全错了。每次尝试使用它时,我都必须使用 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;

关于mocha.js - Sequelize 同步不是一个功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47272498/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com