【问题标题】:Error trying to unit test Mongoose schema validation with Jest尝试使用 Jest 对 Mongoose 模式验证进行单元测试时出错
【发布时间】:2019-01-09 16:51:14
【问题描述】:

我是 Jest 的新手,尝试设置一个简单的测试脚本:

"use strict"

// Local dependencies
const userModel = require('./user.model');

// Setting controllers
describe("Users endpoint", () => {
    describe("Validating user schema", () => {
        it("Should return an error if name property is missing", () => {
            const user = new userModel();

            user.validate((error) => {
                expect(error.errors.name.kind).toBe("required");
            });
        });
    });
});

运行 Jest 时出现以下错误:

SyntaxError: Identifier 'global' has already been declared

  2 |
  3 | // Local dependencies
> 4 | const userModel = require('./user.model');

我在 Google 上搜索并没有找到与“全局”标识符相关的任何内容。

任何帮助将不胜感激。

谢谢,

史蒂夫

【问题讨论】:

  • 你的笑话设置是什么?默认情况下它可能会在另一个文件夹中查找...
  • @Akrion,这行“FAIL web/api/user/user.test.js”是否确认 jest 正在寻找正确的位置?我什至尝试添加 testRegex 然后 testMatch 没有成功。我有由 --init 生成的默认配置和节点环境。
  • @Akrion,错误似乎指向“必需(。”部分。
  • const userModel = require('./user.model') 应该是const userModel = require('./user/model')
  • @Akrion,不是因为我的文件名为 user.model.js。但我只是尝试删除“require”语句和对 userModel 的所有引用,并且测试通过了。所以问题似乎与“要求”有关。

标签: node.js unit-testing mongoose jestjs


【解决方案1】:

好吧,在深入挖掘之后,我发现问题出在我的 require 脚本中的 const 全局变量上:

const global = require(path.join(__dirname, '..', 'config', 'config'));

如果我将“全局”名称更改为其他任何内容(即 globalTest),它将起作用。

似乎不允许使用“全局”。

【讨论】:

    猜你喜欢
    • 2019-10-03
    • 2021-05-07
    • 2014-05-17
    • 2023-03-12
    • 1970-01-01
    • 2013-10-17
    • 1970-01-01
    • 2020-12-30
    • 2020-11-12
    相关资源
    最近更新 更多