【发布时间】: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