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.
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
Although I am still relatively new to Express.js, I think I have gotten fairly familiar with it, but there is one thing that I just can't figure out.
Why does Express log the server object (listed below) log itself in the console, even though I never specified a console.log method to list it?
I wouldn't mind it since it's a test project, but it clutters up the console and I would like to find a way to disable it. Is there a option in the express function maybe?
Server {
insecureHTTPParser: undefined,
_events: [Object: null prototype] {
request: [Function: app] EventEmitter {
_events: [Object: null prototype],
_eventsCount: 1,
_maxListeners: undefined,
setMaxListeners: [Function: setMaxListeners],
getMaxListeners: [Function: getMaxListeners],
emit: [Function],
addListener: [Function: addListener],
on: [Function: addListener],
prependListener: [Function: prependListener],
once: [Function: once],
prependOnceListener: [Function: prependOnceListener],
removeListener: [Function: removeListener],
off: [Function: removeListener],
removeAllListeners: [Function: removeAllListeners],
listeners: [Function: listeners],
rawListeners: [Function: rawListeners],
listenerCount: [Function: listenerCount],
eventNames: [Function: eventNames],
init: [Function: init],
defaultConfiguration: [Function: defaultConfiguration],
lazyrouter: [Function: lazyrouter],
handle: [Function: handle],
use: [Function: use],
route: [Function: route],
engine: [Function: engine],
param: [Function: param],
set: [Function: set],
path: [Function: path],
enabled: [Function: enabled],
disabled: [Function: disabled],
enable: [Function: enable],
disable: [Function: disable],
acl: [Function],
bind: [Function],
checkout: [Function],
connect: [Function],
copy: [Function],
delete: [Function],
get: [Function],
head: [Function],
link: [Function],
lock: [Function],
'm-search': [Function],
merge: [Function],
mkactivity: [Function],
mkcalendar: [Function],
mkcol: [Function],
move: [Function],
notify: [Function],
options: [Function],
patch: [Function],
post: [Function],
pri: [Function],
propfind: [Function],
proppatch: [Function],
purge: [Function],
put: [Function],
rebind: [Function],
report: [Function],
search: [Function],
source: [Function],
subscribe: [Function],
trace: [Function],
unbind: [Function],
unlink: [Function],
unlock: [Function],
unsubscribe: [Function],
all: [Function: all],
del: [Function],
render: [Function: render],
listen: [Function: listen],
request: [IncomingMessage],
response: [ServerResponse],
cache: {},
engines: {},
settings: [Object],
locals: [Object: null prototype],
mountpath: '/'
},
connection: [Function: connectionListener],
listening: [Function: bound onceWrapper] { listener: [Function] }
},
_eventsCount: 3,
_maxListeners: undefined,
_connections: 0,
_handle: TCP {
reading: false,
onconnection: [Function: onconnection],
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
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