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
Related
I want to ask about mock mongoose find.
Let's say I have 2 method mongoose model find like this :
let resultA = await ModelA.find()
and let resultB = await ModelA.find().lean().
These 2 is called in different utils. I tried with mockImplementation like this :
mockMongooseFind.mockImplementation(() => {
return {
lean: jest.fn().mockResolvedValue(resultValueMockFind),
};
});
I
t only work when called method lean but not work when not called method lean.
The result with lean is proper data. But when get the result when not use lean is will be like this :
{ lean:
{ [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] } }.
How I make the proper mock for this case?
Get the better function for mock the mongoose method
My dependency includes os and fs with require. I didn't notice any issues with my unit tests until I ran in a Jenkins env which gave this error:
StorageDirectoryResolutionError: Storage directory resolution failedUnsupportedFilePlatform: Platform not supported for file operations
I updated my Jest config to be like this:
moduleNameMapper: {
'^os$': '<rootDir>/tests/dependency-mocks/os.js',
'^fs$': '<rootDir>/tests/dependency-mocks/fs.js',
},
I am mocking os and fs, even though error is around fs, to ensure things are same between my machine and Jenkins.
My os.js is tiny:
module.exports = {
homedir: () => '/user/home',
platform: () => 'darwin',
release: () => 'some release',
};
I have an os.ts file in __mocks__ like this:
export default {
homedir: () => '/user/home',
platform: jest.fn().mockReturnValue('darwin'),
release: jest.fn().mockReturnValue('some release'),
};
My actual file has this issue:
const os = require('os');
console.log(os); // my exported object is on a default key
{ default:
{ homedir: [Function: homedir],
platform:
{ [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] },
release:
{ [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] } } }
This is where it gets very weird. If I do NOT use moduleNameMapper, the dependency does NOT use my mock file. When I do use moduleNameMapper it ignores the .js file for moduleNameMapper and goes to my .ts file in __mocks__. I realized this when I added a random key to the mock and saw the update in console log.
I need the dependency to use os.release() without the object being nested within default.
The answer was really simple. Changed export default {} in mock files to module.exports = {}.
My project uses import/export for nearly everything. Due to the system it runs on, we have to use const fs = require('fs') instead of import fs from 'fs'; The mocks using export had no issue until moduleNameMapper got thrown into the mix.
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();
});
about 2 years ago, I wrote a node.js module that loads an existing module (jsts) and adds some functions to it. Here is a minimal example:
global.jsts = require("jsts");
global.jsts.algorithm.test = function() {console.log("hi")}
global.jsts.algorithm.test();
I ran it in node (v0.10.18) and it printed
hi
Now, I run the same code in nodejs (v4.2.6) and it prints:
TypeError: global.jsts.algorithm.test is not a function
Is there a way to make it work with the current version of nodejs?
EDIT: I also did:
global.jsts.algorithm.x = 1
console.log(global.jsts.algorithm)
and here is the output:
{ Centroid:
{ [Function: ge]
area2: [Function],
centroid3: [Function],
getCentroid: [Function] },
CGAlgorithms:
{ [Function: he]
orientationIndex: [Function],
signedArea: [Function],
distanceLineLine: [Function],
isPointInRing: [Function],
computeLength: [Function],
isCCW: [Function],
locatePointInRing: [Function],
distancePointLinePerpendicular: [Function],
computeOrientation: [Function],
distancePointLine: [Function],
isOnLine: [Function],
CLOCKWISE: -1,
RIGHT: -1,
COUNTERCLOCKWISE: 1,
LEFT: 1,
COLLINEAR: 0,
STRAIGHT: 0 },
ConvexHull:
{ [Function: me]
extractCoordinates: [Function],
RadialComparator: { [Function: ye] polarCompare: [Function] } },
InteriorPointArea:
{ [Function: oi]
centre: [Function],
avg: [Function],
SafeBisectorFinder: { [Function: ai] getBisectorY: [Function] } },
InteriorPointLine: [Function: ui],
InteriorPointPoint: [Function: li],
RobustLineIntersector: { [Function: ae] nearestEndpoint: [Function] },
MCPointInRing: { [Function: Ii] MCSelecter: [Function: Ni] },
MinimumBoundingCircle:
{ [Function: wi]
pointWitMinAngleWithX: [Function],
lowestPoint: [Function],
pointWithMinAngleWithSegment: [Function] },
MinimumDiameter:
{ [Function: Li]
nextIndex: [Function],
computeC: [Function],
getMinimumDiameter: [Function],
getMinimumRectangle: [Function],
computeSegmentForLine: [Function] } }
I have phantom server running which recieves a request with a cookie attached inside header. I have to use this cookie while opening a page from phantom. To be more precise, I have a string that I need to add as a cookie while opening a page. I have installed phantom using node module model(npm install phantom). Below is my code which I'm trying but I cannot see any cookies :
phantom.create(function(ph){
ph.createPage(function (page) {
console.log(page);
var cookieAdded = ph.addCookie({
'name': 'OSF Cookie',
'value': req.headers.cookie,
'domain': req.headers.host
});
console.log(cookieAdded);
page.open(url, function (status) {
if (status == 'success') {
console.log("Success");
page.getCookies(function(cookie){
console.log(cookie);
});
page.evaluate(
function () {
console.log(document.headers);
return document.documentElement.outerHTML;
},
function (content) {
// console.log(content);
res.send(content);
console.log('RESPONSE SEND')
ph.exit();
});
}
else {
console.log("Status Failed");
ph.exit();
}
})
});
});
[EDIT]Below is the output :
http://localhost:5000/dashboard/
{ url: 'http://localhost:5000/dashboard/' }
osf=5540e22b8f6ac302b117a4cd.DWKdATsCvxskYqL-QfQYSjmYMvI
{ set: [Function],
get: [Function],
open: [Function],
close: [Function],
includeJs: [Function],
sendEvent: [Function],
release: [Function],
uploadFile: [Function],
goBack: [Function],
goForward: [Function],
reload: [Function],
switchToFrame: [Function],
switchToMainFrame: [Function],
switchToParentFrame: [Function],
switchToFocusedFrame: [Function],
onConsoleMessage: [Function],
onError: [Function],
onResourceRequested: [Function],
injectJs: [Function],
evaluate: [Function],
render: [Function],
getContent: [Function],
getCookies: [Function],
renderBase64: [Function],
setHeaders: [Function],
setContent: [Function],
setViewportSize: [Function],
setPaperSize: [Function],
setZoomFactor: [Function],
setFileOnPicker: [Function],
_evaluate: [Function],
_onResourceRequested: [Function] }
undefined
Success
[]
RESPONSE SEND