Related
I have looked at How to test getDerivedStateFromProps with Jest and Enzyme but it is not working for me. here is my test
it('should be red processing only, routing, security grey while bg tasks are running', () => {
component = mount(
<ProcessingStatus store={store}/>
);
const instance = component.instance();
//console.log(instance)
component.setProps({ processing_status: {
header:{
error: true,
message: 'This comms matrix is currently processing flows',
statusCode: 200
},
body: {}
} });
console.log(component.state())
console.log(component.props())
expect(component.find(TrafficLight).length).toEqual(3);
expect(component.find(TrafficLight).at(0).props().RedOn).toEqual(true);
expect(component.find(TrafficLight).at(0).props().AmberOn).toEqual(false);
expect(component.find(TrafficLight).at(0).props().GreenOn).toEqual(false);
});
component.state() or instance.state is always empty {}.
This is the contents of component.props()
{ store:
{ getState: [Function: getState],
getActions: [Function: getActions],
dispatch:
{ [Function: mockConstructor]
_isMockFunction: true,
getMockImplementation: [Function],
mock: [Getter/Setter],
mockClear: [Function],
mockReset: [Function],
mockRestore: [Function],
mockReturnValueOnce: [Function],
mockResolvedValueOnce: [Function],
mockRejectedValueOnce: [Function],
mockReturnValue: [Function],
mockResolvedValue: [Function],
mockRejectedValue: [Function],
mockImplementationOnce: [Function],
mockImplementation: [Function],
mockReturnThis: [Function],
mockName: [Function],
getMockName: [Function] },
clearActions: [Function: clearActions],
subscribe: [Function: subscribe],
replaceReducer: [Function: replaceReducer] },
processing_status:
{ header:
{ error: true,
message: 'This comms matrix is currently processing flows',
statusCode: 200 },
body: {} } }
I need this to be triggered as depending on my props values the state changes and renders other conditions.
If it is a connected component it needs to be retrieved differently.
component = mount(
<ProcessingStatus store={store}/>
);
const instance = component.find('ProcessingStatus').instance();
component.setProps({ processing_status: {
header:{
error: true,
message: 'This comms matrix is currently processing flows',
statusCode: 200
},
body: {}
} });
console.log(instance.state);
Provided me with
console.log tests/jest/components/common/ProcessingStatus/index.test.js:122
{ nextStep: 'This comms matrix is currently processing flows' }
What is not clear in previous answers is if there are connected or not and if shallow or mount is being used
I am having a little trouble with retrieving the data from a table using knex select.
I would like to do something like this
function getUserData(userId){
let user = knex.select('xp','money','rolls','twenty').from('users').where('user_id', userId);
return user;
}
user = getUserData(userId);
user.xp; // do something with this value
but this outputs the following (if i console.log it), but not the requested info from the Select query, unless i am just not sure how to retrieve it:
Builder {
client:
Client_MySQL {
config: { client: 'mysql', connection: [Object] },
connectionSettings:
{ host: '127.0.0.1',
user: 'XXXXXXXXXX',
password: 'XXXXXXXXXX',
database: 'XXXXXXXXXX' },
driver:
{ createConnection: [Function: createConnection],
createPool: [Function: createPool],
createPoolCluster: [Function: createPoolCluster],
createQuery: [Function: createQuery],
escape: [Function: escape],
escapeId: [Function: escapeId],
format: [Function: format],
raw: [Function: raw] },
pool:
Pool {
creator: [Function: create],
destroyer: [Function: destroy],
validate: [Function: validate],
log: [Function],
acquireTimeoutMillis: 60000,
createTimeoutMillis: 30000,
idleTimeoutMillis: 30000,
reapIntervalMillis: 1000,
createRetryIntervalMillis: 200,
propagateCreateError: true,
min: 2,
max: 10,
used: [],
free: [],
pendingCreates: [],
pendingAcquires: [],
destroyed: false,
interval: null },
valueForUndefined:
Raw {
client: [Circular],
sql: 'DEFAULT',
bindings: undefined,
_wrappedBefore: undefined,
_wrappedAfter: undefined,
_debug: undefined },
_events:
{ start: [Function],
query: [Function],
'query-error': [Function],
'query-response': [Function] },
_eventsCount: 4,
makeKnex: [Function: makeKnex] },
and: [Circular],
_single: { table: 'users', only: false },
_statements:
[ { grouping: 'columns', value: [Array] },
{ grouping: 'where',
type: 'whereBasic',
column: 'user_id',
operator: '=',
value: '341007826375802900',
not: false,
bool: 'and' } ],
_method: 'select',
_debug: undefined,
_joinFlag: 'inner',
_boolFlag: 'and',
_notFlag: false }
I'll write some more words here, as it requires me to do so, since it is mostly code. I hope this will be enough words.
The query run asynchronous, so you need to explicitly wait for it to finish. One way to do this is using promises:
knex.select('xp','money','rolls','twenty').from('users').where('user_id', userId)
.then(data => console.log(data));
Also make sure that the connection with the database is already established.
After config database just called an async function it will worked
const knex = require('knex')({
client: 'sqlite3',
connection: {
filename: './mydb.db',
},
useNullAsDefault: true
});
(async function(){
const posts = await knex('data');
console.log(posts)
})()
In this code i am using this sql query
SELECT * FROM data
Using Node, Sinon, Chai, proxyquire for fetch, and Mocha
How come this sinon spy assertion fooCallback1.should.have.been.called; is failing to be called once? I see with console.log(fooCallback1) in the source code that the callCount is 1.
This is the first and only test...so I don't see a reason to reset the spy.
function setLight(...args) {
var request;
var lightNumber;
var alertName;
var callback1;
var callback2;
var callback3;
[request, lightNumber, alertName,
callback1, callback2, callback3] = args;
return fetch(request)
.then(status)
.then(toJSON)
.then(() => {
if(Boolean(callback1)) {
console.log('one')
callback1(lightNumber);
console.log(callback1);
}
before(()=> {
fetch = sinon.stub().returnsPromise();
var response = {
status: 200,
json: () => { 'foo' }
};
fetch.resolves(response);
fetchHelper = proxy('../lib/fetch-helper', {'node-fetch': fetch});
});
it('should run fetch for light effect and shutoff', (done)=> {
var fooCallback1 = sinon.spy();
fetchHelper.setLight('foo', 123, 'foo-alert', fooCallback1);
fetch.should.have.been.called;
fooCallback1.should.have.been.called;
done();
});
1) when executing setLight should run fetch for light effect and shutoff:
AssertionError: expected spy to have been called at least once, but it was never called
at Context.it (test/fetch-helper.js:24:34)
when executing setLight
1) should run fetch for light effect and shutoff
one
{ [Function: proxy]
isSinonProxy: true,
formatters:
{ c: [Function: c],
n: [Function: n],
D: [Function: D],
C: [Function: C],
t: [Function: t],
'*': [Function: *] },
reset: [Function: reset],
invoke: [Function: invoke],
named: [Function: named],
getCall: [Function: getCall],
getCalls: [Function: getCalls],
calledBefore: [Function: calledBefore],
calledAfter: [Function: calledAfter],
calledImmediatelyBefore: [Function: calledImmediatelyBefore],
calledImmediatelyAfter: [Function: calledImmediatelyAfter],
withArgs: [Function: withArgs],
matches: [Function: matches],
printf: [Function: printf],
calledOn: [Function],
alwaysCalledOn: [Function],
calledWith: [Function],
calledWithMatch: [Function],
alwaysCalledWith: [Function],
alwaysCalledWithMatch: [Function],
calledWithExactly: [Function],
alwaysCalledWithExactly: [Function],
neverCalledWith: [Function],
neverCalledWithMatch: [Function],
threw: [Function],
alwaysThrew: [Function],
returned: [Function],
alwaysReturned: [Function],
calledWithNew: [Function],
alwaysCalledWithNew: [Function],
callArg: [Function],
callArgWith: [Function],
callArgOn: [Function],
callArgOnWith: [Function],
yield: [Function],
invokeCallback: [Function],
yieldOn: [Function],
yieldTo: [Function],
yieldToOn: [Function],
spyCall: { [Function: createSpyCall] toString: [Function: toString] },
called: true,
notCalled: false,
calledOnce: true,
calledTwice: false,
calledThrice: false,
callCount: 1,
firstCall:
{ proxy: [Circular],
thisValue: undefined,
args: [ 123 ],
returnValue: undefined,
exception: undefined,
callId: 11,
errorWithCallStack:
Error
at Function.invoke (/home/one/github/lifx-weather/node_modules/sinon/lib/sinon/spy.js:205:19)
at proxy (/home/one/github/lifx-weather/node_modules/sinon/lib/sinon/spy.js:97:22)
at fetch.then.then.then (/home/one/github/lifx-weather/lib/fetch-helper.js:52:9)
at process._tickCallback (internal/process/next_tick.js:103:7) },
secondCall: null,
thirdCall: null,
lastCall:
{ proxy: [Circular],
thisValue: undefined,
args: [ 123 ],
returnValue: undefined,
exception: undefined,
callId: 11,
errorWithCallStack:
Error
at Function.invoke (/home/one/github/lifx-weather/node_modules/sinon/lib/sinon/spy.js:205:19)
at proxy (/home/one/github/lifx-weather/node_modules/sinon/lib/sinon/spy.js:97:22)
at fetch.then.then.then (/home/one/github/lifx-weather/lib/fetch-helper.js:52:9)
at process._tickCallback (internal/process/next_tick.js:103:7) },
args: [ [ 123 ] ],
returnValues: [ undefined ],
thisValues: [ undefined ],
exceptions: [ undefined ],
callIds: [ 11 ],
errorsWithCallStack:
[ Error
at Function.invoke (/home/one/github/lifx-weather/node_modules/sinon/lib/sinon/spy.js:205:19)
at proxy (/home/one/github/lifx-weather/node_modules/sinon/lib/sinon/spy.js:97:22)
at fetch.then.then.then (/home/one/github/lifx-weather/lib/fetch-helper.js:52:9)
at process._tickCallback (internal/process/next_tick.js:103:7) ],
displayName: 'spy',
toString: [Function: toString],
instantiateFake: [Function: create],
id: 'spy#11' }
- should set normal alert lock on
- should set normal alert lock off after time
0 passing (15ms)
2 pending
1 failing
1) when executing setLight should run fetch for light effect and shutoff:
AssertionError: expected spy to have been called at least once, but it was never called
at Context.it (test/fetch-helper.js:27:34)
Here is another way I wrote the test and still same result:
before((done)=> {
fetch = sinon.stub().returnsPromise();
fetchHelper = proxy('../lib/fetch-helper', {'node-fetch': fetch});
done()
});
after(()=> {
});
it('should run fetch for light effect and shutoff', (done)=> {
function fooCallback1() { console.log('aaaaaaaaaaaaaaaaaaaa') }
var foo = sinon.spy(fooCallback1)
fetchHelper.setLight('foo', 123, 'foo-alert', fooCallback1);
var response = {
status: 200,
json: () => { 'foo' }
};
fetch.resolves(response);
fetch.should.have.been.called;
foo.should.have.been.called;
done();
});
when executing setLight
one
aaaaaaaaaaaaaaaaaaaa
1) should run fetch for light effect and shutoff
- should set normal alert lock on
- should set normal alert lock off after time
0 passing (10ms)
2 pending
1 failing
1) when executing setLight should run fetch for light effect and shutoff:
AssertionError: expected fooCallback1 to have been called at least once, but it was never called
at Context.it (test/fetch-helper.js:28:25
fetchHelper.setLight() is asynchronous, but your test isn't waiting for it to complete, so the order in which the code is run is something like this:
fetchHelper.setLight()
fetch(request)
fetch.should.have.been.called
fooCallback1.should.have.been.called
done()
console.log('one')
callback1(lightNumber)
console.log(callback1)
You need to rewrite the test so it will wait for the callback to get called. You don't use a spy for that, but a regular callback function in which you test the assertion(s):
it('should run fetch for light effect and shutoff', done => {
fetchHelper.setLight('foo', 123, 'foo-alert', () => {
fetch.should.have.been.called;
done();
});
});
In addition to robertklep's excellent answer, here is a alternate way I got it to work. I call the fetch resolve after calling the fetch wrapper setLight:
it('should run fetch for light effect and shutoff', (done)=> {
var foo = sinon.spy()
fetchHelper.setLight('foo', 123, 'foo-alert', foo);
fetch.resolves(response);
fetch.should.have.been.called;
foo.should.have.been.called;
done();
});
I'm having trouble getting a working connection via nmp's mssql package.
Here's a quick look at my code:
var sql = require('mssql');
var sqlConfig = {
user: 'NodeUser',
password: 'test',
server: '10.211.55.3',
database: 'NodeJs'
}
sql.connect(sqlConfig, function(err){
if(err != null)
console.log(err);
console.log(sql);
});
Which seems to connect fine, but when I try to use it (in a route class):
var sql = require('mssql');
bookRouter.route('/')
.get(function(req, res){
var req = sql.Request();
req.query('select * from books', function(err, recordset){
console.log(recordset);
});
res.render('BookListView', {
title: 'Hello from Books',
nav: nav,
books: books
});
});
I get "TypeError: Cannot read property 'query' of undefined" on the req.query line. It seems like an issue with the connection? The only useful thing I could think to pull was the result of the "console.log(sql);" line above:
{ connect: [Function],
close: [Function],
on: [Function],
Connection:
{ [Function: Connection]
EventEmitter:
{ [Function: EventEmitter]
EventEmitter: [Circular],
usingDomains: false,
defaultMaxListeners: [Getter/Setter],
init: [Function],
listenerCount: [Function] },
usingDomains: false,
defaultMaxListeners: 10,
init: [Function],
listenerCount: [Function],
__super__:
EventEmitter {
domain: undefined,
_events: undefined,
_maxListeners: undefined,
setMaxListeners: [Function: setMaxListeners],
getMaxListeners: [Function: getMaxListeners],
emit: [Function: emit],
addListener: [Function: addListener],
on: [Function: addListener],
once: [Function: once],
removeListener: [Function: removeListener],
removeAllListeners: [Function: removeAllListeners],
listeners: [Function: listeners],
listenerCount: [Function: listenerCount] } },
Transaction:
{ [Function: Transaction]
EventEmitter:
{ [Function: EventEmitter]
EventEmitter: [Circular],
usingDomains: false,
defaultMaxListeners: [Getter/Setter],
init: [Function],
listenerCount: [Function] },
usingDomains: false,
defaultMaxListeners: 10,
init: [Function],
listenerCount: [Function],
__super__:
EventEmitter {
domain: undefined,
_events: undefined,
_maxListeners: undefined,
setMaxListeners: [Function: setMaxListeners],
getMaxListeners: [Function: getMaxListeners],
emit: [Function: emit],
addListener: [Function: addListener],
on: [Function: addListener],
once: [Function: once],
removeListener: [Function: removeListener],
removeAllListeners: [Function: removeAllListeners],
listeners: [Function: listeners],
listenerCount: [Function: listenerCount] } },
Request:
{ [Function: Request]
EventEmitter:
{ [Function: EventEmitter]
EventEmitter: [Circular],
usingDomains: false,
defaultMaxListeners: [Getter/Setter],
init: [Function],
listenerCount: [Function] },
usingDomains: false,
defaultMaxListeners: 10,
init: [Function],
listenerCount: [Function],
__super__:
EventEmitter {
domain: undefined,
_events: undefined,
_maxListeners: undefined,
setMaxListeners: [Function: setMaxListeners],
getMaxListeners: [Function: getMaxListeners],
emit: [Function: emit],
addListener: [Function: addListener],
on: [Function: addListener],
once: [Function: once],
removeListener: [Function: removeListener],
removeAllListeners: [Function: removeAllListeners],
listeners: [Function: listeners],
listenerCount: [Function: listenerCount] } },
Table: { [Function: Table] fromRecordset: [Function] },
PreparedStatement:
{ [Function: PreparedStatement]
EventEmitter:
{ [Function: EventEmitter]
EventEmitter: [Circular],
usingDomains: false,
defaultMaxListeners: [Getter/Setter],
init: [Function],
listenerCount: [Function] },
usingDomains: false,
defaultMaxListeners: 10,
init: [Function],
listenerCount: [Function],
__super__:
EventEmitter {
domain: undefined,
_events: undefined,
_maxListeners: undefined,
setMaxListeners: [Function: setMaxListeners],
getMaxListeners: [Function: getMaxListeners],
emit: [Function: emit],
addListener: [Function: addListener],
on: [Function: addListener],
once: [Function: once],
removeListener: [Function: removeListener],
removeAllListeners: [Function: removeAllListeners],
listeners: [Function: listeners],
listenerCount: [Function: listenerCount] } },
ConnectionError:
{ [Function: ConnectionError]
captureStackTrace: [Function: captureStackTrace],
stackTraceLimit: 10,
prepareStackTrace: undefined,
__super__: [Error] },
TransactionError:
{ [Function: TransactionError]
captureStackTrace: [Function: captureStackTrace],
stackTraceLimit: 10,
prepareStackTrace: undefined,
__super__: [Error] },
RequestError:
{ [Function: RequestError]
captureStackTrace: [Function: captureStackTrace],
stackTraceLimit: 10,
prepareStackTrace: undefined,
__super__: [Error] },
PreparedStatementError:
{ [Function: PreparedStatementError]
captureStackTrace: [Function: captureStackTrace],
stackTraceLimit: 10,
prepareStackTrace: undefined,
__super__: [Error] },
ISOLATION_LEVEL:
{ READ_UNCOMMITTED: 1,
READ_COMMITTED: 2,
REPEATABLE_READ: 3,
SERIALIZABLE: 4,
SNAPSHOT: 5 },
DRIVERS: [ 'msnodesql', 'tedious', 'tds', 'msnodesqlv8' ],
TYPES:
{ VarChar: [sql.VarChar],
NVarChar: [sql.NVarChar],
Text: [sql.Text],
Int: [sql.Int],
BigInt: [sql.BigInt],
TinyInt: [sql.TinyInt],
SmallInt: [sql.SmallInt],
Bit: [sql.Bit],
Float: [sql.Float],
Numeric: [sql.Numeric],
Decimal: [sql.Decimal],
Real: [sql.Real],
Date: [sql.Date],
DateTime: [sql.DateTime],
DateTime2: [sql.DateTime2],
DateTimeOffset: [sql.DateTimeOffset],
SmallDateTime: [sql.SmallDateTime],
Time: [sql.Time],
UniqueIdentifier: [sql.UniqueIdentifier],
SmallMoney: [sql.SmallMoney],
Money: [sql.Money],
Binary: [sql.Binary],
VarBinary: [sql.VarBinary],
Image: [sql.Image],
Xml: [sql.Xml],
Char: [sql.Char],
NChar: [sql.NChar],
NText: [sql.NText],
TVP: [sql.TVP],
UDT: [sql.UDT],
Geography: [sql.Geography],
Geometry: [sql.Geometry],
Variant: [sql.Variant] },
MAX: 65535,
map:
[ { js: [Function: String], sql: [sql.NVarChar] },
{ js: [Function: Number], sql: [sql.Int] },
{ js: [Function: Boolean], sql: [sql.Bit] },
{ js: [Function: Date], sql: [sql.DateTime] },
{ js: [Object], sql: [sql.VarBinary] },
{ js: [Object], sql: [sql.TVP] },
register: [Function] ],
fix: true,
Promise: [Function: Promise],
VarChar: [sql.VarChar],
VARCHAR: [sql.VarChar],
NVarChar: [sql.NVarChar],
NVARCHAR: [sql.NVarChar],
Text: [sql.Text],
TEXT: [sql.Text],
Int: [sql.Int],
INT: [sql.Int],
BigInt: [sql.BigInt],
BIGINT: [sql.BigInt],
TinyInt: [sql.TinyInt],
TINYINT: [sql.TinyInt],
SmallInt: [sql.SmallInt],
SMALLINT: [sql.SmallInt],
Bit: [sql.Bit],
BIT: [sql.Bit],
Float: [sql.Float],
FLOAT: [sql.Float],
Numeric: [sql.Numeric],
NUMERIC: [sql.Numeric],
Decimal: [sql.Decimal],
DECIMAL: [sql.Decimal],
Real: [sql.Real],
REAL: [sql.Real],
Date: [sql.Date],
DATE: [sql.Date],
DateTime: [sql.DateTime],
DATETIME: [sql.DateTime],
DateTime2: [sql.DateTime2],
DATETIME2: [sql.DateTime2],
DateTimeOffset: [sql.DateTimeOffset],
DATETIMEOFFSET: [sql.DateTimeOffset],
SmallDateTime: [sql.SmallDateTime],
SMALLDATETIME: [sql.SmallDateTime],
Time: [sql.Time],
TIME: [sql.Time],
UniqueIdentifier: [sql.UniqueIdentifier],
UNIQUEIDENTIFIER: [sql.UniqueIdentifier],
SmallMoney: [sql.SmallMoney],
SMALLMONEY: [sql.SmallMoney],
Money: [sql.Money],
MONEY: [sql.Money],
Binary: [sql.Binary],
BINARY: [sql.Binary],
VarBinary: [sql.VarBinary],
VARBINARY: [sql.VarBinary],
Image: [sql.Image],
IMAGE: [sql.Image],
Xml: [sql.Xml],
XML: [sql.Xml],
Char: [sql.Char],
CHAR: [sql.Char],
NChar: [sql.NChar],
NCHAR: [sql.NChar],
NText: [sql.NText],
NTEXT: [sql.NText],
TVP: [sql.TVP],
UDT: [sql.UDT],
Geography: [sql.Geography],
GEOGRAPHY: [sql.Geography],
Geometry: [sql.Geometry],
GEOMETRY: [sql.Geometry],
Variant: [sql.Variant],
VARIANT: [sql.Variant],
pool: { max: 10, min: 0, idleTimeoutMillis: 30000 },
connection: { userName: '', password: '', server: '' },
init: [Function] }
I can't help but notice the lack of credentials here. Any thoughts? Thanks.
Looks like an issue of asynchronisity, try doing it on the request directly, like the mssql npm example:
var sql = require('mssql');
bookRouter.route('/')
.get(function(req, res){
sql.Request().query('select * from books')
.then(function(recordset){
console.log(recordset);
res.render('BookListView', {
title: 'Hello from Books',
nav: nav,
books: books
});
}).catch(function(err){
// some error handling
});
});
Just cannot get my head around this after 10 hours of trying:
if I
users.findById(req.body.user_id,function(e,doc){});
and console.log the doc returned, all looks good:
{ _id: 54dcad6de4b01007caacb0cd,
username: 'realizertest',
password: '******************************',
first_name: 'Realizer',
second_name: 'Test',
display_name: 'Realizer Test',
email: 'system#realizerlabs.com' }
However, when trying to access the included fields, e.g. by:
user = users.findById(req.body.user_id,function(e,doc){});
var user_email = user.email;
I just get undefined. The user object looks like this:
{ col:
{ manager:
{ driver: [Object],
helper: [Object],
collections: [Object],
options: [Object],
_events: {} },
driver:
{ _construct_args: [],
_native: [Object],
_emitter: [Object],
_state: 2,
_connect_args: [Object] },
helper: { toObjectID: [Function], id: [Ob
name: 'users',
col:
{ _construct_args: [],
_native: [Object],
_emitter: [Object],
_state: 2,
_skin_db: [Object],
_collection_args: [Object],
id: [Object],
emitter: [Object] },
options: {} },
type: 'findOne',
opts: { fields: {}, safe: true },
domain: null,
_events:
{ error: [ [Function], [Function] ],
success: [ [Function], [Function] ] },
_maxListeners: 10,
emitted: {},
ended: false,
success: [Function],
error: [Function],
complete: [Function],
resolve: [Function],
fulfill: [Function],
reject: [Function],
query: { _id: 54dcad6de4b01007caacb0cd } }
I've also tried user.query.email but get the same result.
The findById obviously doesn't return a JSON object that I can use in this way.
How can I get at these fields?
It's an async call, so you need to use the callback, you can't assign that function to a variable:
users.findById(req.body.user_id,function(e,doc){
var user = doc;
console.log(user); //should see the object now, and access the props
});