我正在使用karma-jasmine,webpact運行單元測試。 我試圖用書架在mysql數據庫中插入一條記錄。 我收到以下錯誤消息:ReferenceError:沒有定義書架
的ReferenceError:書架沒有定義 在module.exports.addCategoryWithProducts(app_serv /訂單/測試/ order.util.spec.js:94215:2) 在對象。 (app_serv/order/test/order.util.spec.js:94059:3) at ContextKarma.loaded(http://localhost:9876/context.js:151:12) TypeError:無法在對象處讀取未定義的 屬性'then'。 (app_serv /訂單/測試/ order.util.spec.js:94074:4)
類型錯誤:_this.driver.createConnection不是函數
我的代碼:
var knex = require('knex')({
client: 'mysql',
connection: {
host : 'localhost',
user : 'user1',
password : 'toto',
database : 'totoDb',
charset : 'utf8'
}
});
module.exports = require('bookshelf')(knex);
module.exports.addCategoryWithProducts = function(categoryToAdd) {
bookshelf.transaction(function(t) {
var products = categoryToAdd.products;
var tableProd = [];
//if (!req.params.idCategory || req.params.idCategory ==0) {
Category.forge({
name: categoryToAdd.name,
code: categoryToAdd.code,
tax_percentage: categoryToAdd.tax_percentage,
description: categoryToAdd.description
})
.save(null, { transacting: t })
.then(function(category) {
for (var i = 0; i < products.length; i++) {
tableProd.push({
barcode: products[ i ].barcode,
cip_13: products[ i ].cip_13,
category_id: category.id,
quantity: products[ i ].quantity,
retail_price: products[ i ].retail_price,
description: products[ i ].description,
name: products[ i ].name,
inn: products[ i ].inn,
kind: products[ i ].kind,
comment: products[ i ].comment,
status: products[ i ].status,
critical_threshold: products[ i ].critical_threshold,
max_threshold: products[ i ].max_threshold,
date_end: products[ i ].date_end
});
}
Products.forge(tableProd)
.invokeThen('save', null, { transacting: t })
.then(function(products) {
//console.log('inside insert of collection '+ JSON.stringify({category : category.toJSON(), produits: products}))
//res.json({error : false, data: {category : category.toJSON(), products: products}});
t.commit();
return Promise.resolve(category.related('products'));
})
.catch(function(err) {
return Promise.reject(err.message);
//console.log('Erreur dans Products.forge: ' + err.message);
res.status(500)
.json({ error: true, code: err.code, message: err.message });
})
})
.catch(function(err) {
return Promise.reject(err.message)
//console.log('Erreur dans Products.forge: ' + err.message);
//res.status(500).json({error: true, code : err.code, message: err.message});
})
});
}
單元測試代碼:
it("addCategoryWithProducts", function(done){
addCategoryWithProducts(categoryMock)
.then(function(catWithPrds){
expect(catWithPrds).toBeDefined();
expect(catWithPrds.products).toBeDefined();
expect(catWithPrds.products.length).toBe(3);
})
);
嘗試失敗了許多解決方案之後,我決定找你幫忙。
你的代碼看起來不完整的。 「書架」在哪裏以及如何定義?它看起來像'require('bookshelf')(knex);'屬於另一個源文件。 – flaviodesousa
是的,它在另一個文件中。 我不認爲問題在那裏。 – Evabila
也許不是,但是你的錯誤明確提到'bookshelf'沒有被定義。所以第一個想到的人會看到它在哪裏以及如何定義。如果您正確分割代碼段,它可能會有所幫助。 – flaviodesousa