Using cypress-plugin-snapshots returns .toMatchSnapshot is not a function - plugins

I'm trying to use cypress-plugin-snapshots to take some snapshots of JavaScript objects.
I have followed the Configure Cypress.io instructions on https://www.npmjs.com/package/cypress-plugin-snapshots but when I run my test (below) I receive the following error
1) Check snapshots Should match snapshot:
TypeError: expectedData.toMatchSnapshot is not a function
at Context.<anonymous> (https://www.bbc.com/__cypress/tests?p=cypress/integration/data_driven.js-917:24:18)
My test file is:
describe('Check snapshots', function () {
it('Should match snapshot', () => {
const expectedData = {
fonts:
[ { familyName: 'Helvetica', isCustomFont: false, glyphCount: 10 },
{ familyName: 'Gurmukhi MN', isCustomFont: false, glyphCount: 33 } ]
}
expectedData.toMatchSnapshot();
});
});
I'm relatively new to both JS (and Cypress) so I am not sure exactly what it is I am doing wrong. If anyone has experience sorting this issue out I'd be really grateful for some input.

You simply need to wrap your object with expect:
expect(expectedData).toMatchSnapshot()

Related

how to get query parameter in action2 in sails

I dont know how to set up route according to REST for the search request url like this
localhost:1337/system?id=10
After that, how can we get parameter from the above request in action 2 like this
action2(inputs,exits)
I want to follow best practice for web api in sails. Please hint me to solve and recommend any handy documents.
Thanks in advance
For the Actions2 format, you'd use inputs.id, after properly defining the inputs, of course. For more information, consult the documentation on Actions and Controllers. This would need more finishing, but it gets your input and a function. You'd want to add in your exits, and some real logic, of course, and probably some decent descriptions.
module.exports = {
inputs: {
id: {
type: 'number',
required: true
}
},
exits: {
success: { ... },
error: { ... }
},
fn: async function (inputs, exits) {
var myId = inputs.id;
return exits.success(myId);
}
}

MongoDB: can't return random document from collection

I'm working on a word game and am trying to return a random wordpair (my collection) on a page load. I'm using Express and have adapted my code from this tutorial if that's of any use.
A GET request renders my page just fine, and I'm trying to send a random WordPair object alongside the title:
router.get('/', function(req, res, next) {
res.render('play', { title: 'play', random_wordpair: wordpair_controller.wordpair_random});
});
The wordpair_random function is here inside a controller file I've made (which also successfully manages listing the wordpairs and creating new ones etc).
// Get random WordPair
exports.wordpair_random = function() {
WordPair.aggregate(
[{
$sample: {
size: 1
}
}]
)
.exec(function(err, random_wordpair) {
if (err) {
return next(err);
}
console.log(random_wordpair);
return random_wordpair;
});
};
Then inside a play.pug template, I'm simply trying to display this result:
h3 random wordpair selection is: #{random_wordpair}
But all I can see is the function rendered as HTML text. Can anyone tell me what I'm doing wrong?
I also understand looking at the documentation for MongoDB $sample aggregation that I need to be calling my function on the database object, but I've seen various examples and some don't do this. When I try calling db.wordpair.aggregate(...) (or WordPair or wordpairs as it appears in mLab) directly after initializing db in my app.js file, I get undefined errors. My db object doesn't seem to contain the correct data for this request.
Thanks!
I guess you're writing this in Node.JS. A core feature in Node.JS is non-blocking IO model. That means, the code won't wait for a database call to complete to move on.
Another concept you need to get it right is that Node.JS, being a variation of JavaScript, in nature is a functional programming. Assigning a function to a property of a JSON object like below won't cause the function to execute. It simply creates a pointer to the function body, that's why your application prints the function itself.
{ title: 'play', random_wordpair: wordpair_controller.wordpair_random}
To fix this, use a callback
exports.wordpair_random = function(callback) {
WordPair.aggregate([$sample: {size: 1}}]).exec(callback);
};
Then in you web function:
router.get('/', function(req, res, next) {
wordpair_controller.wordpair_random(function(err, result) {
//Handle errors if needed.
res.render('play', { title: 'play', random_wordpair:result });
})
});

Unable to add tasks from the provideTasks function

Following on from this question I have another question about how to implement the provideTasks method of the registerTaskProvider.
Using the npm extension as an example I have tried to implement a basic function, to simply return a single, hard-coded, task. This would then be extended to actually parse a file, ready to add dynamic tasks. However, I have been unable to get this to work.
The code that I am trying is:
vscode.workspace.findFiles('**/*.cake').then((files) => {
if (files.length === 0) {
return emptyTasks;
}
try {
const result: vscode.Task[] = [];
result.push(new vscode.Task({type: 'cake', script: 'NuGet-Restore'} as CakeTaskDefinition, 'Nuget-Restore', 'cake', new vscode.ShellExecution('npm install'), []));
console.log(result);
return Promise.resolve(result);
} catch (e) {
return Promise.resolve(emptyTasks);
}
});
Even though I can see that result contains a Task, I don't see it populated in the Task drop down list.
Can anyone offer any help in why this is not working?
A repository with the current code can be found here.
UPDATE
I have just edited the above code to be the following:
try {
const result: vscode.Task[] = [];
result.push(new vscode.Task({ type: 'cake', script: 'NuGet-Restore' } as CakeTaskDefinition, 'Nuget-Restore', 'cake', new vscode.ShellExecution('npm install'), []));
console.log(result);
return Promise.resolve(result);
} catch (e) {
return Promise.resolve(emptyTasks);
}
By not including the initial findFiles function, it correctly populates the Task Menu with the single hard-coded Task. Why is it that I can't do the return from within the findFiles method? I now suspect that this is a TypeScript/JavaScript problem, rather than one with the provideTasks function, but I am still looking for some help on this.
What is the recommended approach for what I am trying to do? Thanks in advance!
You need to return findFiles to ensure the tasks are actually returned from the task provider:
return vscode.workspace.findFiles('**/*.cake').then((files) => {
...
});
Using "noImplicitReturns": true in your tsconfig.json—or, even better, "strict": true—can help catch bugs like this

How do I send a PDF to Watson's Document Conversion service without writing it to disk first?

I am trying to convert this document (http://www.redbooks.ibm.com/redbooks/pdfs/ga195486.pdf) to answer units in Watson's Document Conversion service using the watson-developer-cloud node.js library.
In the actual program (not this test program), I am retrieving the document and converting it on-the-fly, without writing it to disk first. I have done this before with other documents, but the latest version of the library (v 1.7.0) seems to have changed and it no longer works the way I was using it. But even before I started using the latest version, this particular document would not convert.
The annotated test code that I am using is below. I have tried several ways to get this to work, the variations of which are all commented out under var opts={ below. You have to uncomment one of them at a time to see the results.
'use strict';
var bluemix = require('./bluemix');
var extend=require('util')._extend;
var fs=require('fs');
var watson=require('watson-developer-cloud');
var streams = require('memory-streams');
var dcCredentials = extend({
url: '<url>',
version: 'v1',
username: '<username>',
password: '<password>'
}, bluemix.getServiceCreds('document_conversion')); // VCAP_SERVICES
var document_conversion = watson.document_conversion(dcCredentials);
var bookpdf=getBook('ga195486.pdf');
convert(bookpdf);
function getBook(filename)
{
var bl=fs.readFileSync(filename,'utf8');
return bl;
}
function convert(content)
{
var opts={ //uncomment ONE of these
// file: new Buffer(content), //See message #1 below
// file: {value: new Buffer(content), options: {}}, //see message #2 below
// file: {value: new Buffer(content), options: {contentType: "application/pdf"}}, //This used to work. See message #2 (again) below
// file: new streams.ReadableStream(content),//see message #3 below
conversion_target: "ANSWER_UNITS",
content_type:'application/pdf'
};
document_conversion.convert(opts,
function (err, response)
{
if (err)
{
console.log("Error converting doc: ", err);
}
else if (response.answer_units.length==0)
{
var msg="No answer units";
console.log(msg,response);
}
else
{
console.log('Works!');
console.dir(response);
}
}
);
}
//Message #1: This returns:
// No answer units { source_document_id: '',
// timestamp: '2016-05-23T16:18:23.825Z',
// media_type_detected: 'application/pdf',
// metadata: [],
// answer_units: [],
// warnings:
// [ { phase: 'pdf',
// warning_id: 'empty_input_to_converter',
// description: 'The input provided to the converter phase is empty or doesn\'t contain text that can be converted.' },
// { phase: 'normalized_html',
// warning_id: 'empty_input_to_converter',
// description: 'The input HTML document has no body content.' },
// { phase: 'answer_units',
// warning_id: 'empty_input_to_converter',
// description: 'The input provided to the converter phase is empty or doesn\'t contain text that can be converted.' } ] }
//Message #2: These return:
///home/david/git/ccb-contentbridge/node_modules/watson-developer-cloud/node_modules/request/node_modules/combined-stream/node_modules/delayed-stream/lib/delayed_stream.js:33
// source.on('error', function() {});
//
//TypeError: source.on is not a function
// at Function.DelayedStream.create (/home/david/git/ccb-contentbridge/node_modules/watson-developer-cloud/node_modules/request/node_modules/combined-stream/node_modules/delayed-stream/lib/delayed_stream.js:33:10)
// at FormData.CombinedStream.append (/home/david/git/ccb-contentbridge/node_modules/watson-developer-cloud/node_modules/request/node_modules/combined-stream/lib/combined_stream.js:43:37)
// at FormData.append (/home/david/git/ccb-contentbridge/node_modules/watson-developer-cloud/node_modules/request/node_modules/form-data/lib/form_data.js:68:3)
// at appendFormValue (/home/david/git/ccb-contentbridge/node_modules/watson-developer-cloud/node_modules/request/request.js:339:21)
// at Request.init (/home/david/git/ccb-contentbridge/node_modules/watson-developer-cloud/node_modules/request/request.js:352:11)
// at new Request (/home/david/git/ccb-contentbridge/node_modules/watson-developer-cloud/node_modules/request/request.js:142:8)
// at request (/home/david/git/ccb-contentbridge/node_modules/watson-developer-cloud/node_modules/request/index.js:55:10)
// at createRequest (/home/david/git/ccb-contentbridge/node_modules/watson-developer-cloud/lib/requestwrapper.js:134:10)
// at DocumentConversion.convert (/home/david/git/ccb-contentbridge/node_modules/watson-developer-cloud/services/document_conversion/v1.js:134:10)
// at convert (/home/david/git/ccb-contentbridge/testRedbooks.js:35:24)
//Message #3: This returns and then it hangs there:
//Error converting doc: { code: 400, error: 'Error in the web application' }
Can someone please tell me what I am doing wrong?
That particular file is larger than what the Document Conversion service can currently handle. Unfortunately I don't have very good info on exactly what the limits are right now, but the team is aware of this and looking into making improvements.
If you can provide an example that worked previously but broke with the v1.7.0 of the node.js library, I'll take a look at that and hopefully be able to provide better info.
Oh, and specifying 'utf8' on your fs.readfileSync() call may be causing some of the trouble you're experiencing.
Looks like the limit for Doc Con is 50 MB per this and our documents are smaller than that... must be some other problem.

Meteor onRendered function and access to Collections

When user refresh a certain page, I want to set some initial values from the mongoDB database.
I tried using the onRendered method, which in the documentation states will run when the template that it is run on is inserted into the DOM. However, the database is not available at that instance?
When I try to access the database from the function:
Template.scienceMC.onRendered(function() {
var currentRad = radiationCollection.find().fetch()[0].rad;
}
I get the following error messages:
Exception from Tracker afterFlush function:
TypeError: Cannot read property 'rad' of undefined
However, when I run the line radiationCollection.find().fetch()[0].rad; in the console I can access the value?
How can I make sure that the copy of the mongoDB is available?
The best way for me was to use the waitOn function in the router. Thanks to #David Weldon for the tip.
Router.route('/templateName', {
waitOn: function () {
return Meteor.subscribe('collectionName');
},
action: function () {
// render all templates and regions for this route
this.render();
}
});
You need to setup a proper publication (it seems you did) and subscribe in the route parameters. If you want to make sure that you effectively have your data in the onRendered function, you need to add an extra step.
Here is an example of how to make it in your route definition:
this.templateController = RouteController.extend({
template: "YourTemplate",
action: function() {
if(this.isReady()) { this.render(); } else { this.render("yourTemplate"); this.render("loading");}
/*ACTION_FUNCTION*/
},
isReady: function() {
var subs = [
Meteor.subscribe("yoursubscription1"),
Meteor.subscribe("yoursubscription2")
];
var ready = true;
_.each(subs, function(sub) {
if(!sub.ready())
ready = false;
});
return ready;
},
data: function() {
return {
params: this.params || {}, //if you have params
yourData: radiationCollection.find()
};
}
});
In this example you get,in the onRendered function, your data both using this.data.yourData or radiationCollection.find()
EDIT: as #David Weldon stated in comment, you could also use an easier alternative: waitOn
I can't see your collection, so I can't guarantee that rad is a key in your collection, that said I believe your problem is that you collection isn't available yet. As #David Weldon says, you need to guard or wait on your subscription to be available (remember it has to load).
What I do in ironrouter is this:
data:function(){
var currentRad = radiationCollection.find().fetch()[0].rad;
if (typeof currentRad != 'undefined') {
// if typeof currentRad is not undefined
return currentRad;
}
}