Execute command for editor scroll in VSCode - scroll

That should work:
const vscode = require('vscode')
async function commentLine() {
const success = await vscode.commands
.executeCommand('vscode.editorScroll', {
to:'down',
by: 'halfPage',
revealCursor: true,
});
console.log(success)
}
but upon running this code after a user action, I receive 'vscode.revealCursor` is unknown command in a warning modal.
Any idea why this doesn't work?

The actual error message is:
command 'vscode.editorScroll' not found
The problem is not revealCursor, the problem is the vscode. prefix on the command name. Change the executeCommand first argument to just "editorScroll" and it works.
Also this particular command does not return anything, so success is undefined.

Related

Referencing Add Command in Webdriverio

I'm using webdriverio (version 6.14.13) and mocha to run my native app tests via Browserstack.
I've created a command script in my command folder, called closeCmp.command.js, as the code was being reused in many tests.
browser.addCommand('cmpDismissal', async function() {
cmpDismissal = $('~ACCEPT AND CLOSE');
if (await this.cmpDismissal.isExisting()) {
this.cmpDismissal.click();
this.cmpDismissal.waitForExist({ reverse: true });
}
},true);
But my question is, how do I reference this in my test script?
I tried what I thought would work;
describe('testing the app cmp.....', () => {
it('close cmp', async () => {
await browser.commands.cmpDismissal();
but when I run the test, the command script is not being run.
It doesn't return an actual failure message, but when I go into Browserstack I can see that the button has not been clicked, indication that the new command has not been executed.
Am I calling it incorrectly in my test script, or is the actual command script the issue here? Thanks

Combined resolvers always throw "cannot read property 'apply' of undefined" error

I am trying to attach the following guard:
export const isSupplier=(_,__,{me})=>{
me.role==="supplier" ? skip : new ForbiddenError('Not authenticated as supplier.');
}
To a resolver, like this:
addProductNow:combineResolvers(
isSupplier,
async (_,{name,price,description,url,stock},{dataSources,me})=>{
const supplierId=me.id
console.log(supplierId)
const supplier=await dataSources.SupplierAPI.findSupplierById(supplierId)
const newProduct=await dataSources.ProductAPI.addProduct(name,price,description,url,stock,supplierId,{ttlInSeconds:60*20})
return newProduct
}),
Yet it always returns the error "cannot read property 'apply' of undefined". I have tried to log something in the guard , yet it seems like it never gets executed. After removing the guard from the resolver everything works fine and logging 'me' shows the expected value. Am I doing something wrong ? Thanks !
I'm not sure what you're using for your "guards", but I assume it's because you're not doing or returning anything in this function, and it's expecting a function (what it calls "apply" on):
export const isSupplier=(_,__,{me})=>{
me.role==="supplier" ? skip : new ForbiddenError('Not authenticated as supplier.');
}
Did you mean to do this:
export const isSupplier=(_,__,{me})=>{
return me.role==="supplier" ? skip : new ForbiddenError('Not authenticated as supplier.');
}
Follow-up Edit:
From googling some of your variable names, I assume you're using graphql-resolvers.
In the example they provide, they use "arrow functions with implicit return", which is when you
Don't add Braces around the body of your function
Put the whole thing in one expression
The result of the function becomes whatever the expression after the arrow results in:
const isAuthenticated = (root, args, { user }) => user ? skip : new Error('Not authenticated')
This can be converted to using "explicit returns" by adding braces and the return keyword like this:
const isAuthenticated = (root, args, { user }) => {
return user ? skip : new Error('Not authenticated')
}
Your code as documented, however, added the braces but NOT the return and therefore always returns undefined. Looking at the source code of that library, if you don't return EXACTLY skip it resolves to whatever the return value of your function was (in this case undefined).
Can you share more information about your stack trace to show WHAT is trying to call .apply on what?

Check if an error has been written to the console

I'm trying to find a way to check if an error has been written to the console when running a cypress unit test.
I know how to log something to the console
cy.log('log this to the console');
but not how to check if an error has been written to it.
any suggestions how to read errors from the (browser) console log?
note: probably not the "smart" way to test but sometimes my js libraries which I use would "complain" and write the errors to the browser log. this is to simplify testing.
This does exactly what I needed of catching any error in the console and do an assertion of the logs count. Just add the following in cypress/support/index.js
Cypress.on('window:before:load', (win) => {
cy.spy(win.console, 'error');
cy.spy(win.console, 'warn');
});
afterEach(() => {
cy.window().then((win) => {
expect(win.console.error).to.have.callCount(0);
expect(win.console.warn).to.have.callCount(0);
});
});
There have been some updates since the previous answers.
Because the window is re-created with each cy.visit, Cypress recommends stubbing as a part of the cy.visit command.
cy.visit('/', {
onBeforeLoad(win) {
cy.stub(win.console, 'log').as('consoleLog')
cy.stub(win.console, 'error').as('consoleError')
}
})
//...
cy.get('#consoleLog').should('be.calledWith', 'Hello World!')
cy.get('#consoleError').should('be.calledOnce')
For more details see the official FAQ for stubbing out the console: https://docs.cypress.io/faq/questions/using-cypress-faq.html#How-do-I-spy-on-console-log
And the recipe repository: https://github.com/cypress-io/cypress-example-recipes/tree/master/examples/stubbing-spying__console
Edit: the following does not directly log to terminal when in headless mode, but it nonetheless fails the test on AUT's console.error and displays the error message indirectly, even in the headless terminal, which may be what you want.
I'm not sure exactly what you mean, but let's go through all the places where an output can be logged in cypress, and how to handle several cases.
First, an overview:
To log into the command log, you use:
// from inside your test
cy.log('foo');
To log into devTools console:
// from inside your test
console.log('bar');
To log into terminal, you need to log from within the Cypress' node process:
// from within e.g. your plugin/index.js file
console.log('baz');
How to log AUT's errors to Terminal, Command Log, and fail the test
(note, AUT here stands for Application under test, meaning your application).
I'm also using ansicolor package to make the error red-colored in the terminal, which is optional.
// plugins/index.js
const ansi = require(`ansicolor`);
module.exports = ( on ) => {
on(`task`, {
error ( message ) {
// write the error in red color
console.error( ansi.red(message) );
// play `beep` sound for extra purchase
process.stdout.write(`\u0007`);
return null;
}
});
};
Note: using internal cy.now() command to work around Cypress' tendency to throw Cypress detected that you returned a promise when it (IMO) shouldn't.
(adapted from https://github.com/cypress-io/cypress/issues/300#issuecomment-438176246)
// support/index.js or your test file
Cypress.on(`window:before:load`, win => {
cy.stub( win.console, `error`, msg => {
// log to Terminal
cy.now(`task`, `error`, msg );
// log to Command Log & fail the test
throw new Error( msg );
});
});
Currently there is no straightforward way to do what you are asking but there have been some good discussions on how best to get this information. I copied one solution here but if you follow the github link you can see other solutions proposed.
This snippet was taken from the github issue found here: https://github.com/cypress-io/cypress/issues/300
Just FYI the one easy solution is just to spy on console functions.
cy.window().then((win) => { cy.spy(win.console, "log") })
That will print a command log every time that function is called, and
you could also then assert what has been logged.
Another option depending on why you want to assert that something went wrong is to print the error out under the tests in headless mode. The VP of engineering created an NPM package that does this for you.
Cypress-failed-log
The most easiest way if you simply want to ensure that no error is in the console (which is the most usecase I assume).
# npm
npm install cypress-fail-on-console-error --save-dev
# yarn
yarn add cypress-fail-on-console-error -D
And then add to your support/index.ts file:
import failOnConsoleError from "cypress-fail-on-console-error"
failOnConsoleError()
Now your cypress tests are failing just in time when a console error is printed.
This is the working solution I currently use to check for console errors.
let windowConsoleError;
Cypress.on('window:before:load', (win) => {
windowConsoleError = cy.spy(win.console, 'error');
})
afterEach(() => {
expect(windowConsoleError).to.not.be.called;
})

Sinon useFakeTimers() creates a timeout in before/afterEach

I'm using Sinon with Mocha to test some expiration date values. I used the same code a few months ago and it worked fine, but somewhere between v1.12.x and v1.17.x, something has changed and I can't seem to find the right path.
let sinon = require('sinon');
describe('USER & AUTHENTICATION ENDPOINTS', function(done) {
beforeEach(function() {
this.clock = sinon.useFakeTimers(new Date().getTime());
return fixtures.load(data);
});
afterEach(function() {
this.clock.restore();
return fixtures.clear(data);
});
context('POST /users', function() { ... }
});
I've tried with and without the new Date().getTime() argument.
I've tried passing in and explicitly calling done().
I've tried removing my fixture load/clear processes.
The end result is always the same:
Error: timeout of 5000ms exceeded. Ensure the done() callback is being called in this test.
Has something changed that I just haven't noticed in the documentation? Do I have some kind of error in there that I can't see?
Any thoughts would be appreciated.
UPDATE
So a little more info here. This clearly has something to do with my code, but I'm at a loss.
If I comment every actual test, the tests run and give me a green "0 passing".
If I run an actual test, even one that just this:
context('POST /users', function() {
it('should create a new user', function(done) {
done();
})
});
I'm right back to the timeout. What am I missing?
Mystery solved. It appears to be a conflict between Sinon and versions of Knex > 0.7.6.
Seems to be because pool2 relies on behavior of setTimeout. Using sinon.useFakeTimers(...) replaces several methods including setTimeout with synchronous versions which breaks it. Can fix by replacing with: clock = sinon.useFakeTimers(Number(date), 'Date');
My original code was written in a world where Knex v0.7.6 was the latest version. Now that it's not everything failed even though the code itself was the same. I used the fix mentioned and things look to be fine.
You are passing done to your describe callback in line 2:
describe('USER & AUTHENTICATION ENDPOINTS', function(done) {
Mocha expects you to invoke it... To get rid of the timeout error, just remove the done parameter from the callback.

Catch and Handle CasperError

Using CasperJS how do I catch and handle CasperError?
The default appears to continue execution of the program (which does nothing but propagates the error).
These errors are logged to the console/stdout but I don't seem to see a way (from the docs) to catch and handle these errors.
Example:
this.fillSelectors(selector, data);
May produce:
CasperError: Errors encountered while filling form: form not found
I know I can check to make sure everything exists before calling, but is there a way to catch after the fact? (this applies to many other operations like casper.click as well)
I use something currently like this:
casper.on('error', function(msg,backtrace) {
this.capture('./out/error.png');
throw new ErrorFunc("fatal","error","filename",backtrace,msg);
});
and then I have a custom function ErrorFunc to process array of any warnings or a fatal error.
If you have an unsuccessful click it should throw the casper.on('error'). So you can put custom code there for how you would like to handle the error.
Here's the documentation for Casper events.
var casper = require('casper').create({
onError: function(msg, backtrace) {
this.capture('error.png');
throw new ErrorFunc("fatal","error","filename",backtrace,msg);
}
});
This works pretty well.
(See http://docs.casperjs.org/en/latest/modules/casper.html#index-1)
This is the complete solution for who need it ^^
casper.on('error', function(msg, backtrace) {
this.capture('/tmp/error.png');
console.log('backtrace: ' + JSON.stringify(backtrace, null, 4));
console.log('message: ' + JSON.stringify(msg, null, 4));
console.log('check capture in /tmp/error.png');
casper.exit(1);
})

Resources