javascript - 类型错误 : Attempted to wrap undefined property find as function - NodeJs

标签 javascript node.js mocha.js sinon chai

我正在尝试使用 TDD 方法运行我的测试,如下所示。我在另一个应用程序上运行相同的测试(我复制粘贴它)并且它有效,但在此测试中我收到以下错误:

TypeError: Attempted to wrap undefined property find as function Model file

/* 任务模型 数据库模型 */

const mongoose = require('mongoose');

    try {
      module.exports = mongoose.model('Task');
    } catch (error) {
      const taskSchema = mongoose.Schema({
        title: { type: String, required: true },
        status: { type: Boolean, required: true }
      });
      module.exports = taskSchema;
    }

/* 示例测试 */

'use strict';

const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');
const sinon = require('sinon');
const expect = chai.expect;
const Task = require('../../models/task');
chai.should();
chai.use(chaiAsPromised);

//TEST DRIVEN DEVELOPMENT
describe('Todo Controller', () => {
  const expectedResult = { status: 201, tasks: [{}], message: '' };

  //Testing if the array has a valid status
  it('should get a valid status', done => {
    const TodoMock = sinon.mock(Task);

    TodoMock.expects('find').yields(null, expectedResult);
    Task.find((err, result) => {
      TodoMock.verify();
      TodoMock.restore();
      expect(result.status).to.be.equal(201);
      done();
    });
  });

});

最佳答案

您似乎遇到了一些范围界定问题。我会这样编写模型:

const mongoose = require('mongoose');
const taskSchema;

try {
  taskSchema = mongoose.model('Task');
} catch (error) {
  taskSchema = mongoose.Schema({
    title: { type: String, required: true },
    status: { type: Boolean, required: true }
  });
}

module.exports = taskSchema;

关于javascript - 类型错误 : Attempted to wrap undefined property find as function - NodeJs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58138555/

相关文章:

javascript - 固定位置着色器背景在 Three.js 中?

javascript - 简单的 javascript 在 Shopify 中不起作用

javascript - 如何在javascript中检查php数组的长度

javascript - 当您从后端收到消息时,如何将 ng-repeat 与 socket.io 一起使用?

node.js - 使用我的 Node 应用程序设置 StrongLoop

node.js - 错误: async hook stack has become corrupted in node js

node.js - Lex 聊天机器人错误 : Reached second execution of fulfillment lambda on the same utterance

php - 在 Heroku 上的 Node 中运行 php

node.js - 在nodejs中运行mocha测试用例时出现内存不足异常

unit-testing - 使用 cloud9 的 mocha 测试,从 node.js 执行 mocha 测试