【问题标题】:Mocha Testing a Nested ModelMocha 测试嵌套模型
【发布时间】:2016-12-27 03:01:43
【问题描述】:

尝试为嵌套模型编写测试但无法正常工作:

型号:

const EmployeeSchema = new mongoose.Schema({
  firstName: {type: String, required: true},
  lastName: { type: String, required: true}
});

const CompanySchema = new mongoose.Schema({
  name: { type: String, required: true },
  streetAddress: { type: String, required: true },
  country: { type: String, required: true },
  employees:[EmployeeSchema]    
}, { timestamps: true});

控制器:

function create(req, res, next) {
  const company = new Company({
    name: req.body.name,
    streetAddress: req.body.streetAddress,
    country: req.body.country    
  });

  company.employees.push(req.employees);

  company.save()
    .then(savedCompany => res.json(savedCompany))
    .catch(e => next(e));
}

测试:

    describe('## Company APIs', () => {
      let company = {
        name: "Test Company",
        streetAddress: "123 Fake Street",
        country: "A Country"    
      };
      company.employees.push({firstName: "Jane", lastName: "Doe"});

  describe('# POST /api/company', () => {
    it('should create a new company', (done) => {
      request(app)
        .post('/api/company')
        .send(company)
        .expect(httpStatus.OK)
        .then((res) => {
          expect(res.body.name).to.equal(company.name);
          expect(res.body.streetAddress).to.equal(company.streetAddress);
          expect(res.body.country).to.equal(company.country);
          company = res.body;
          done();
        })
        .catch(done);
    });
  });

以上给出:TypeError: Cannot read property 'push' of undefined

我尝试了其他一些方法,但这是最有希望的结果,由于某种原因,我似乎无法在设置单元测试时填充嵌入式模型。

【问题讨论】:

  • 这可能不是答案,但我在测试中发现了这条线company.employees.push({firstName: "Jane", lastName: "Doe"});。它试图推送公司中不存在的对象employees。而且它不断言company.employees 然后我认为您可以删除该行

标签: express mongoose ecmascript-6 mocha.js


【解决方案1】:

我最终解决了这个问题,希望这对将来的人有所帮助。

测试:

it('should associate an employee with the company', (done) => {    
      var employee = new Employee();
      company.employees.push(employee);      
      request(app)
        .put(`/api/company/${company._id}`)
        .send(company)
        .expect(httpStatus.OK)
        .then((res) => {
          expect(res.body.employees).to.be.an('array')
          expect(res.body.employees).to.contain(employee.id)
          done();
        })
        .catch(done);
    });

控制器: 添加这个来处理多个添加:

if (req.body.employees != null) {      
    req.body.employees.forEach(function(employee) {      
      company.employees.push(employee);
    }, this);
  }  

【讨论】:

    猜你喜欢
    • 2012-07-13
    • 1970-01-01
    • 2016-11-19
    • 1970-01-01
    • 1970-01-01
    • 2019-05-04
    • 2018-05-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多