如何在 Cucumber-JS 步骤定义中使用 Node-mysql 连接到 MySQL?
How to connect to MySQL using Node-mysql in a Cucumber-JS step definition?
我正在尝试通过 world.js 中定义的连接方法,使用 node-mysql 连接到我的 Cucumber-JS stepDefinition 文件中的 MySQL 数据库。不幸的是,它不会连接 return 我的查询结果,我也无法让它向我显示一条错误消息,以帮助我找出哪里出了问题。
我过去使用过 Cucumber-JVM,但对 JavaScript 和 node.js 还是个新手。我已经使用相同的方法创建了一个独立的 js 文件(模仿 world.js),并从另一个测试脚本成功调用了它(模仿 stepDefinitions.js);它连接并 return 愉快地记录,所以这可能是由于我对 JavaScript 中的上下文的误解,或者在 Cucumber-JS 使用世界的方式中,也许...
stepDefinitons.js:
'use strict';
var ImportStepDefinitions = function() {
this.World = require('../support/world.js').World;
this.Given(/^I have a clean Magento database$/, function (callback) {
this.connectToDatabase();
//this.clearDatabase();
callback();
});
this.When(/^I import the test data file "([^"]*)"$/, function (testDataFile, callback) {
//this.importTestFile();
callback.pending();
});
this.Then(/^an attribute set is created called "([^"]*)"$/, function (attributeSetName, callback) {
//this.validateAttributeSet();
callback.pending();
});
};
module.exports = ImportStepDefinitions;
world.js:
'use strict';
var World = function World(callback) {
var mysql = require('mysql');
var host = 'localhost';
var user = 'user';
var password = 'password';
var database = 'magento';
var connection = mysql.createConnection({
host: host,
user: user,
password: password,
database: database
});
this.connectToDatabase = function () {
connection.connect(function(err){
if(err) {
console.error("Connection error: " + err.stack);
return;
}
console.log("Connection state 1 = ", connection);
});
connection.query('SELECT * FROM admin_user', function (err, rows, fields) {
if (err) {
console.error("Query error: " + err.stack);
return;
}
console.log("ROWS ====== ", rows[0]);
recordDetail = rows[0];
});
console.log("Connection state 2 = ", connection);
connection.end();
};
this.clearDatabase = function(scriptName) {
//Run import script in sql so starting with a fresh magento database
};
this.importTestFile = function(testFileName) {
//Need to call import.php with file location
};
this.validateAttributeSet = function(attributeSetName) {
//Use magento object (?) to check attribute set exists as expected
};
callback();
};
module.exports.World = World;
当我执行代码时,我没有从 connection.connect() 返回任何信息,既没有错误也没有日志,没有记录从 connection.query() 中注销,连接在 'connection state 2 ='显示(在底部右侧)_connectCalled 值为 true,但状态为断开连接且 threadId 为 null:
Connection state 2 = { domain:
{ domain: null,
_events: { error: [Function: handleScenarioException] },
_maxListeners: undefined,
members: [],
id: 'domain-1437457225974' },
_events: {},
_maxListeners: undefined,
config:
{ host: 'localhost',
port: 3306,
localAddress: undefined,
socketPath: undefined,
user: 'user',
password: 'password',
database: 'magento',
connectTimeout: 10000,
insecureAuth: false,
supportBigNumbers: false,
bigNumberStrings: false,
dateStrings: false,
debug: undefined,
trace: true,
stringifyObjects: false,
timezone: 'local',
flags: '',
queryFormat: undefined,
pool: undefined,
ssl: false,
multipleStatements: false,
typeCast: true,
maxPacketSize: 0,
charsetNumber: 33,
clientFlags: 455631 },
_socket:
{ _connecting: true,
_hadError: false,
_handle:
{ fd: -1,
reading: false,
owner: [Circular],
onread: [Function: onread],
onconnection: null,
writeQueueSize: 0 },
_parent: null,
_host: 'localhost',
_readableState:
{ objectMode: false,
highWaterMark: 16384,
buffer: [],
length: 0,
pipes: null,
pipesCount: 0,
flowing: true,
ended: false,
endEmitted: false,
reading: false,
sync: true,
needReadable: false,
emittedReadable: false,
readableListening: false,
defaultEncoding: 'utf8',
ranOut: false,
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null,
resumeScheduled: true },
readable: false,
domain:
{ domain: null,
_events: [Object],
_maxListeners: undefined,
members: [],
id: 'domain-1437457225974' },
_events:
{ end: [Object],
finish: [Function: onSocketFinish],
_socketEnd: [Function: onSocketEnd],
data: [Function],
error: [Function],
connect: [Object],
timeout: [Object] },
_maxListeners: undefined,
_writableState:
{ objectMode: false,
highWaterMark: 16384,
needDrain: false,
ending: false,
ended: false,
finished: false,
decodeStrings: false,
defaultEncoding: 'utf8',
length: 0,
writing: false,
corked: 0,
sync: true,
bufferProcessing: false,
onwrite: [Function],
writecb: null,
writelen: 0,
bufferedRequest: null,
lastBufferedRequest: null,
pendingcb: 0,
prefinished: false,
errorEmitted: false },
writable: true,
allowHalfOpen: false,
destroyed: false,
bytesRead: 0,
_bytesDispatched: 0,
_pendingData: null,
_pendingEncoding: '',
_idleTimeout: 10000,
_idleNext: { _idleNext: [Circular], _idlePrev: [Circular] },
_idlePrev: { _idleNext: [Circular], _idlePrev: [Circular] },
_idleStart: 2735419 },
_protocol:
{ domain:
{ domain: null,
_events: [Object],
_maxListeners: undefined,
members: [],
id: 'domain-1437457225974' },
_events:
{ data: [Function],
end: [Object],
handshake: [Function],
unhandledError: [Function],
drain: [Function],
enqueue: [Function] },
_maxListeners: undefined,
readable: true,
writable: true,
_config:
{ host: 'localhost',
port: 3306,
localAddress: undefined,
socketPath: undefined,
user: 'user',
password: 'password',
database: 'magento',
connectTimeout: 10000,
insecureAuth: false,
supportBigNumbers: false,
bigNumberStrings: false,
dateStrings: false,
debug: undefined,
trace: true,
stringifyObjects: false,
timezone: 'local',
flags: '',
queryFormat: undefined,
pool: undefined,
ssl: false,
multipleStatements: false,
typeCast: true,
maxPacketSize: 0,
charsetNumber: 33,
clientFlags: 455631 },
_connection: [Circular],
_callback: null,
_fatalError: null,
_quitSequence: null,
_handshakeSequence:
{ domain: [Object],
_events: [Object],
_maxListeners: undefined,
_callback: [Object],
_callSite: [Error],
_ended: false,
_timeout: undefined,
_idleNext: null,
_idlePrev: null,
_idleStart: null,
_idleTimeout: undefined,
_repeat: null,
_config: [Object],
_handshakeInitializationPacket: null },
_handshaked: false,
_ended: false,
_destroyed: false,
_queue: [ [Object], [Object] ],
_handshakeInitializationPacket: null,
_parser:
{ _supportBigNumbers: false,
_buffer: <Buffer >,
_longPacketBuffers: [],
_offset: 0,
_packetEnd: null,
_packetHeader: null,
_packetOffset: null,
_onError: [Function],
_onPacket: [Function],
_nextPacketNumber: 0,
_encoding: 'utf-8',
_paused: false } },
_connectCalled: true,
state: 'disconnected',
threadId: null }
好的,我相信我已经找到了解决方案,所以 post 在这里为以类似方式苦苦挣扎的其他人提供帮助。请随时 post 更好地解释这里发生的原因和情况!
我没有正确实现回调,如 cucumber.js 文档所述;我需要将它传递给被调用的函数,并用它来表示被调用函数何时完成:
StepDefinitions.js:
...
this.Given(/^I have a clean Magento database$/, function (callback) {
//callback passed into function
this.connectToDatabase(callback);
...
world.js:
...
//callback now passed into function
this.connectToDatabase = function(callback) {
var host = 'localhost';
var user = 'user';
var password = 'password';
var database = 'magento';
var connection = mysql.createConnection({
host: host,
user: user,
password: password,
database: database
});
connection.connect(function(err){
if(err) {
console.error("Connection error: " + err.stack);
return;
}
});
connection.query('SELECT * FROM admin_user', function (err, rows) {
if (err) {
console.error("Query error: " + err.stack);
} else {
console.log(rows[0]);
}
});
/*callback used to signify end of function, ensuring all actions are
actually completed before the rest of the scenario steps are completed
by cucumber.js*/
connection.end(callback);
};
....
我正在尝试通过 world.js 中定义的连接方法,使用 node-mysql 连接到我的 Cucumber-JS stepDefinition 文件中的 MySQL 数据库。不幸的是,它不会连接 return 我的查询结果,我也无法让它向我显示一条错误消息,以帮助我找出哪里出了问题。
我过去使用过 Cucumber-JVM,但对 JavaScript 和 node.js 还是个新手。我已经使用相同的方法创建了一个独立的 js 文件(模仿 world.js),并从另一个测试脚本成功调用了它(模仿 stepDefinitions.js);它连接并 return 愉快地记录,所以这可能是由于我对 JavaScript 中的上下文的误解,或者在 Cucumber-JS 使用世界的方式中,也许...
stepDefinitons.js:
'use strict';
var ImportStepDefinitions = function() {
this.World = require('../support/world.js').World;
this.Given(/^I have a clean Magento database$/, function (callback) {
this.connectToDatabase();
//this.clearDatabase();
callback();
});
this.When(/^I import the test data file "([^"]*)"$/, function (testDataFile, callback) {
//this.importTestFile();
callback.pending();
});
this.Then(/^an attribute set is created called "([^"]*)"$/, function (attributeSetName, callback) {
//this.validateAttributeSet();
callback.pending();
});
};
module.exports = ImportStepDefinitions;
world.js:
'use strict';
var World = function World(callback) {
var mysql = require('mysql');
var host = 'localhost';
var user = 'user';
var password = 'password';
var database = 'magento';
var connection = mysql.createConnection({
host: host,
user: user,
password: password,
database: database
});
this.connectToDatabase = function () {
connection.connect(function(err){
if(err) {
console.error("Connection error: " + err.stack);
return;
}
console.log("Connection state 1 = ", connection);
});
connection.query('SELECT * FROM admin_user', function (err, rows, fields) {
if (err) {
console.error("Query error: " + err.stack);
return;
}
console.log("ROWS ====== ", rows[0]);
recordDetail = rows[0];
});
console.log("Connection state 2 = ", connection);
connection.end();
};
this.clearDatabase = function(scriptName) {
//Run import script in sql so starting with a fresh magento database
};
this.importTestFile = function(testFileName) {
//Need to call import.php with file location
};
this.validateAttributeSet = function(attributeSetName) {
//Use magento object (?) to check attribute set exists as expected
};
callback();
};
module.exports.World = World;
当我执行代码时,我没有从 connection.connect() 返回任何信息,既没有错误也没有日志,没有记录从 connection.query() 中注销,连接在 'connection state 2 ='显示(在底部右侧)_connectCalled 值为 true,但状态为断开连接且 threadId 为 null:
Connection state 2 = { domain:
{ domain: null,
_events: { error: [Function: handleScenarioException] },
_maxListeners: undefined,
members: [],
id: 'domain-1437457225974' },
_events: {},
_maxListeners: undefined,
config:
{ host: 'localhost',
port: 3306,
localAddress: undefined,
socketPath: undefined,
user: 'user',
password: 'password',
database: 'magento',
connectTimeout: 10000,
insecureAuth: false,
supportBigNumbers: false,
bigNumberStrings: false,
dateStrings: false,
debug: undefined,
trace: true,
stringifyObjects: false,
timezone: 'local',
flags: '',
queryFormat: undefined,
pool: undefined,
ssl: false,
multipleStatements: false,
typeCast: true,
maxPacketSize: 0,
charsetNumber: 33,
clientFlags: 455631 },
_socket:
{ _connecting: true,
_hadError: false,
_handle:
{ fd: -1,
reading: false,
owner: [Circular],
onread: [Function: onread],
onconnection: null,
writeQueueSize: 0 },
_parent: null,
_host: 'localhost',
_readableState:
{ objectMode: false,
highWaterMark: 16384,
buffer: [],
length: 0,
pipes: null,
pipesCount: 0,
flowing: true,
ended: false,
endEmitted: false,
reading: false,
sync: true,
needReadable: false,
emittedReadable: false,
readableListening: false,
defaultEncoding: 'utf8',
ranOut: false,
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null,
resumeScheduled: true },
readable: false,
domain:
{ domain: null,
_events: [Object],
_maxListeners: undefined,
members: [],
id: 'domain-1437457225974' },
_events:
{ end: [Object],
finish: [Function: onSocketFinish],
_socketEnd: [Function: onSocketEnd],
data: [Function],
error: [Function],
connect: [Object],
timeout: [Object] },
_maxListeners: undefined,
_writableState:
{ objectMode: false,
highWaterMark: 16384,
needDrain: false,
ending: false,
ended: false,
finished: false,
decodeStrings: false,
defaultEncoding: 'utf8',
length: 0,
writing: false,
corked: 0,
sync: true,
bufferProcessing: false,
onwrite: [Function],
writecb: null,
writelen: 0,
bufferedRequest: null,
lastBufferedRequest: null,
pendingcb: 0,
prefinished: false,
errorEmitted: false },
writable: true,
allowHalfOpen: false,
destroyed: false,
bytesRead: 0,
_bytesDispatched: 0,
_pendingData: null,
_pendingEncoding: '',
_idleTimeout: 10000,
_idleNext: { _idleNext: [Circular], _idlePrev: [Circular] },
_idlePrev: { _idleNext: [Circular], _idlePrev: [Circular] },
_idleStart: 2735419 },
_protocol:
{ domain:
{ domain: null,
_events: [Object],
_maxListeners: undefined,
members: [],
id: 'domain-1437457225974' },
_events:
{ data: [Function],
end: [Object],
handshake: [Function],
unhandledError: [Function],
drain: [Function],
enqueue: [Function] },
_maxListeners: undefined,
readable: true,
writable: true,
_config:
{ host: 'localhost',
port: 3306,
localAddress: undefined,
socketPath: undefined,
user: 'user',
password: 'password',
database: 'magento',
connectTimeout: 10000,
insecureAuth: false,
supportBigNumbers: false,
bigNumberStrings: false,
dateStrings: false,
debug: undefined,
trace: true,
stringifyObjects: false,
timezone: 'local',
flags: '',
queryFormat: undefined,
pool: undefined,
ssl: false,
multipleStatements: false,
typeCast: true,
maxPacketSize: 0,
charsetNumber: 33,
clientFlags: 455631 },
_connection: [Circular],
_callback: null,
_fatalError: null,
_quitSequence: null,
_handshakeSequence:
{ domain: [Object],
_events: [Object],
_maxListeners: undefined,
_callback: [Object],
_callSite: [Error],
_ended: false,
_timeout: undefined,
_idleNext: null,
_idlePrev: null,
_idleStart: null,
_idleTimeout: undefined,
_repeat: null,
_config: [Object],
_handshakeInitializationPacket: null },
_handshaked: false,
_ended: false,
_destroyed: false,
_queue: [ [Object], [Object] ],
_handshakeInitializationPacket: null,
_parser:
{ _supportBigNumbers: false,
_buffer: <Buffer >,
_longPacketBuffers: [],
_offset: 0,
_packetEnd: null,
_packetHeader: null,
_packetOffset: null,
_onError: [Function],
_onPacket: [Function],
_nextPacketNumber: 0,
_encoding: 'utf-8',
_paused: false } },
_connectCalled: true,
state: 'disconnected',
threadId: null }
好的,我相信我已经找到了解决方案,所以 post 在这里为以类似方式苦苦挣扎的其他人提供帮助。请随时 post 更好地解释这里发生的原因和情况!
我没有正确实现回调,如 cucumber.js 文档所述;我需要将它传递给被调用的函数,并用它来表示被调用函数何时完成:
StepDefinitions.js:
...
this.Given(/^I have a clean Magento database$/, function (callback) {
//callback passed into function
this.connectToDatabase(callback);
...
world.js:
...
//callback now passed into function
this.connectToDatabase = function(callback) {
var host = 'localhost';
var user = 'user';
var password = 'password';
var database = 'magento';
var connection = mysql.createConnection({
host: host,
user: user,
password: password,
database: database
});
connection.connect(function(err){
if(err) {
console.error("Connection error: " + err.stack);
return;
}
});
connection.query('SELECT * FROM admin_user', function (err, rows) {
if (err) {
console.error("Query error: " + err.stack);
} else {
console.log(rows[0]);
}
});
/*callback used to signify end of function, ensuring all actions are
actually completed before the rest of the scenario steps are completed
by cucumber.js*/
connection.end(callback);
};
....