for example,
stylus file:
.dd
fun()
height:10px
and I use nodejs to complie it
var stylus = require('stylus');
var s = stylus(stylusCode);
s.render(function(err, css) {
if (err) {
grunt.log.error(err);
grunt.fail.warn('Stylus failed to compile.');
callback(css, true);
} else {
callback(css, null);
}
});
in stylus file,"fun" function is undefined,I want it throw a error,but not.
Related
try {
myObject = {
a: JSON.stringify(obj)
};
} catch (err) {
logError(`myMethod :::: ${err.message}`);
}
I wanted to cover catch block under jest testcases but I am new to this jest test cases so I m not getting how to mock Json.stringify and how to throw error?
I am mocking as below. But I am getting error as: TypeError: Invalid JSON Can u please tell me where I am going wrong?
JSON.stringify = jest.fn().mockImplementationOnce(() => { throw new TypeError('Invalid JSON'); });
As I understand it, you want to test the catch part of your code. You can pass an invalid Json as an object.
So, if your function is:
function jestTest(obj) {
try {
myObject = {
a: JSON.stringify(obj)
};
} catch (err) {
logError(`myMethod :::: ${err.message}`);
}
}
module.export = jestTest
then, in your test function, you can use this:
var jestTestObject = require('./jestTest') // this hold your exported module, code which you are testing
JSON.stringify = jest.fn(); // do not mock to return "Invalid Json"
test("CatchPart", () => {
var invalidJson = ({ "a": 1}) // Create invalid json
var logErrorSpy = jest.spyOn(jestTestObject, 'logError') // spy on logError
jestTest(obj); // Invalid object will take it to catch part
expect(logErrorSpy).toHaveBeenCalledTimes(1) // which will call logError once
})
In the code below, when I run in debug mode with a break-point at this line: content.push(data.Body.toString()); I can see that data is inserted to the content array.
However when I run the code normally, content comes back empty.
How can I get it to populate the array for downstream use?
var params = { Bucket: "thebucket", Prefix: "theprefix/" }
var content = [];
function getS3Data()
{
var s3 = new aws.S3();
s3.listObjects(params, function (err, data)
{
if (err) throw err; // an error occurred
else
{
var i;
for (i = 0; i < data.Contents.length; i++)
{
var currentValue = data.Contents[i];
if(currentValue.Key.endsWith(params.Prefix) == false)
{
var goParams = { Bucket: params.Bucket, Key: currentValue.Key };
s3.getObject(goParams, function(err, data)
{
if (err) throw err; //error
content.push(data.Body.toString());
});
};
};
}//else
});//listObjects
}//getS3Data
getS3Data();
console.log(content); //prints empty here when run in non-debug.
The line:
console.log(content)
is being executed before the line:
content.push(data.Body.toString());
the function you are passing as a 2nd argument to s3.listObjects will be executed asynchronously. If you want to log out content you need to do it within the callback function meaning:
s3.listObjects(params, function (err, data) {
if (err) throw err;
else {
// ...
console.log(content)
}
});
A better approach would be to implement getS3Data with Promise so you can run code after the object listing is done for sure.
function getS3Data() {
return new Promise((resolve, reject) => {
if (err) {
reject(err)
} else {
const promises = []
for (const i = 0; i < data.Contents.length; i++) {
const currentValue = data.Contents[i];
if (currentValue.Key.endsWith(params.Prefix) == false) {
const goParams = { Bucket: params.Bucket, Key: currentValue.Key };
promises.push(new Promise((res, rej) => {
s3.getObject(goParams, function (err, data) {
if (err) {
rej(err); //error
} else {
res(data.Body.toString());
}
});
}));
}
}
Promise.all(promises).then(resolve);
}
});
}
getS3Data()
.then(result => { // this will actually be `content` from your code example
console.log(result);
}).catch(error => {
console.error(error);
})
Node.js' documentation has an example very similar to the problem you are experiencing:
Dangers of Mixing Blocking and Non-Blocking Code
The issue arises because the variable content is not set as soon as getS3Data has finished, because it is an asynchronous function. content will be set some time later. But your call to console.log(content); will execute immediately after getS3Data has finished, so at that point content has not been set yet.
You can test that by adding an extra log:
s3.getObject(goParams, function(err, data)
{
if (err) throw err; //error
content.push(data.Body.toString());
console.log("Content has been assigned");
});
And then change the bottom to:
getS3Data();
console.log("getS3Data has finished", content);
It's likely you'll get the messages in this order:
getS3Data has finished
Content has been assigned
I am getting this error
when I am trying to test code on react project:
var amqp = require('amqplib/callback_api');
export function start2 (conn) {
console.log("hello")
amqp.connect('amqp://localhost:8000', function (err, conn) {
conn.createChannel(function(err, ch) {
var q = 'frontend';
var msg = 'Hello!';
ch.assertQueue(q, {durable: false});
// Note: on Node 6 Buffer.from(msg) should be used
ch.sendToQueue(q, new Buffer(msg));
console.log(" [x] Sent %s", msg);
});
setTimeout(function() { conn.close(); process.exit(0) }, 500);
});
}
any help please and thanks.
My app is Working Fine. But I used color picker from http://ruhley.github.io/angular-color-picker/ and some thing went wrong.Now my app is unable to start also. I removed this color picker still same.
error I am getting is
Uncaught TypeError: undefined is not a function inside angular.js at
function createInternalInjector(cache, factory) {
function getService(serviceName, caller) {
if (cache.hasOwnProperty(serviceName)) {
if (cache[serviceName] === INSTANTIATING) {
throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
serviceName + ' <- ' + path.join(' <- '));
}
return cache[serviceName];
} else {
try {
path.unshift(serviceName);
cache[serviceName] = INSTANTIATING;
return cache[serviceName] = factory(serviceName, caller);
} catch (err) {
if (cache[serviceName] === INSTANTIATING) {
delete cache[serviceName];
}
throw err;//<<------GETTING ERROR HERE
} finally {
path.shift();
}
}
}
Problem is solved by updating angular-cookies and angular-resource both to 1.4.0
My goal is to go through a loop asynchronously:
client.js:
abc = function() {
for (var i = 0; i <= 49; i++) {
console.log(i);
Meteor.call('testBla', i)
}
}
server.js
testBla: function(i) {
function asyncCall() {
console.log('inside asyncCall', i)
return 'done';
}
var syncCall = Meteor.wrapAsync(asyncCall);
console.log('a');
var res = syncCall(i);
console.log('b')
return res;
}
Console:
a
inside asyncCall 0
Why does it stuck?
Functions you can pass to Meteor.wrapAsync must have a specific signature : their arguments must end with a callback given 2 arguments : error and result.
Inside an async function body, you must invoke the callback with either an error in case the function fails, or the result if everything is OK.
function asyncHelloWorld(callsCount, callback){
// simulate fake error every 5 calls
if(callsCount % 5 === 0){
callback("error");
}
callback(null,);
}
for(var i = 0; i < 50; i++){
asyncHelloWorld(i, function(error, result){
if(error){
console.log(error.reason);
return;
}
console.log(result);
});
}
You can only wrap functions that respect this signature and behavior, which is a standard inherited from Node.JS.
When you wrap async functions, don't forget to use a try/catch block if you want to handle the potential error.
Meteor.methods({
helloWorld: function(i){
var syncHelloWorld = Meteor.wrapAsync(asyncHelloWorld);
console.log("a");
try{
var res = syncHelloWorld(i);
console.log("b")
return res;
}
catch(exception){
console.log(exception);
console.log("c");
// do not recover, propagates the exception back to the client (standard behavior)
throw exception;
}
}
});