Log Javascript console output in Laravel Dusk - laravel

I am using Laravel 5.6 and Laravel Dusk 3.0.9.
Dusk is pretty handy, but when a test fails on a page where there is some Javascript functionality it can be pretty hard to work out what went wrong. Dusk generates a screenshot, which helps, but what I really need is to see the output from the Javascript console.
Apparently this is possible - Dusk creates a tests/Browser/console directory as part of its installation, and this PR suggests the JS console output is logged, or at least loggable.
There is no documentation (that I can find) about how to actually do that though. Browsing the diffs in that PR, I see a new method logConsole() (later renamed to storeConsoleLog() as #Jonas pointed out in the comments), but I can't seem to get it to do anything, eg:
$browser->visit('/somewhere')
->select('#foo', '2')
->value('#date', '2018-07-29')
->storeConsoleLog('bar')
->assertEnabled('button[type=submit]');
This test fails, and generates a nice screenshot, but there is no sign of any logfile. I've tried moving the position of ->storeConsoleLog('bar') around in the chain, eg first or last, and as a separate line before or after the chain:
$browser->visit('/somewhere')
->...full chain here;
$browser->storeConsoleLog('bar');
But none of them make any difference. My JS has a series of console.log()s which I use when testing myself in a browser, and which will tell me exactly what went wrong. I was expecting this functionality to log those messages.
Am I misunderstanding that PR, is this even possible? If so, how?
UPDATE
By debugging the storeConsoleLog() method in vendor/laravel/dusk/src/Browser.php I can see that the method is being called correctly, but there is no console content to log. If I manually repeat the steps the test is taking in Chrome, there are lines being written to Chrome devtools console, in fact 3 are written on page load. Why can't Dusk see those?
UPDATE 2
I found that if you remove '--headless' from the driver() method in DuskTestCase, the browser will be displayed during tests. You can then display the dev tools for that browser, and watch the console output live as the tests run. It is too fast to really be useful, and if there is an error the browser closes and you lose whatever was on the console anyway (unless there's a way to leave the browser open on failure?), but adding this here in case it is useful to someone!

There is apparently no way to get non-error console output from the browser.
There are other log types, but Chrome only supports browser (used by Dusk) and driver.
You'll probably have to use alerts. But screenshots don't contain alerts, so you have to get the text:
$browser->driver->switchTo()->alert()->getText()
You could also use something like document.write() and check the output on the screenshot.

It is possible. There's an answer here written in Python from 2014 that shows it's been possible since at least that long.
Override \Laravel\Dusk\TestCase::driver:
protected function driver()
{
$desired_capabilities = new DesiredCapabilities([
'browserName' => 'chrome',
'platform' => 'ANY',
]);
// the proper capability to set to get ALL logs stored
$desired_capabilities->setCapability('loggingPrefs', [
'browser' => 'ALL',
'driver' => 'ALL',
]);
// return the driver
return RemoteWebDriver::create(
'http://localhost:9515',
$desired_capabilities
);
}

Related

Cypress tests failing in firefox in pages with polling requests

I have a following test in Cypress:
visit first page with the header A
click on the Go to B Page button
assert that the header of the page is now B
It works fine in Chrome, but failing in Firefox, as on the page B I have some background polling requests, and when cypress switches to another test and those requests get "canceled" away, I get either TypeError: NetworkError when attempting to fetch resource or AbortError: The operation was aborted
All the requests are using fetch api, by the way.
The possibility to mute those errors through the uncaught:exception event seems a bad idea, and so does the idea to do something on the page to cancel the polling, as it is not the thing under testing.
Maybe someone has encoutnered this problem too and got some non-hacky solution?
I had a similar issue with Cypress tests in Firefox and resorted to the slightly hacky solution of using an uncaught:exception handler as you mention. It is possible to filter error messages somewhat at least:
function handleUncaughtException(err){
if (err.message.includes('Request aborted') ) {
console.log("Request aborted. Test will continue. Error:",err);
return false; // return false to make test continue
}
throw err;
}
cy.on('uncaught:exception',handleUncaughtException);
In principle you can cancel this handler when it's no longer needed. In my case though, this stopped the test working, presumably because the request started previous to or after the calls.
cy.removeListener("uncaught:exception", handleUncaughtException)
The Cypress docs have some advice on defining these: see at https://docs.cypress.io/api/events/catalog-of-events#Examples. It may be useful to put the handler in a support file, so that it is applied to all tests.
(See also https://docs.cypress.io/api/events/catalog-of-events#Event-Types and https://nodejs.org/api/events.html#events_emitter_removelistener_eventname_listener).

Using something other than cy.request to seed data in Cypress

I'm using Cypress for end-to-end testing. In my beforeEach, I'm using an SDK I've been provided to seed data on a server (the SDK sends API calls to the server but does not use cy.request inside it). The method on the SDK returns a promise, therefore I figured I could return the promise like so:
beforeEach(() => {
return sdk.createProperty(...);
});
My test then does something like this:
it('displays a property', () => {
cy.visit(`/companies/${appTestData.companyId}/properties`);
...the rest is commented out currently...
}
This actually works as intended, that is, it waits until the server response is returned before running the tests, but I see the following warning in the console when the test actually runs:
Cypress Warning: Cypress detected that you returned a promise in a test, but also invoked one or more cy commands inside of that promise...
I noticed if I change my beforeEach to use cy.then, the warning goes away:
beforeEach(() => {
cy.then(() => sdk.createProperty(...));
});
It seems a bit unnecessary and was kind of a stab in the dark, so I'd like to know if there's a prescribed way of doing what I need to do. I can't change the SDK I'm using to use cy.request, which I assume would also prevent the warning. Thanks.
Probably not what you want to hear, but can I confirm you that using cy.then(...) is the most standard way of waiting for a Promise in Cypress I know of.
After reading your question, I have tried to use Cypress Network Requests features to wait for a fetch('my/url') in a before(), but it doesn't seem to be detecting the request at all.

Cypress seems to have stalled

I'm new to cypress and love the way it is architected. However, I seem to have run into a problem early on for a very simple thing that I'm trying to do.
My workflow is:
1) Visit the site
2) Enter username and password
3) On the next screen, type a number and press submit,
4) On the next screen, select a value from a dropdown and press enter.
5) I get to the landing page of my website.
Cypress works totally fine till step 4). It seems to stall at step 5. The test runner suddenly stalls and without warning or error, shows
"Whoops, there is no test to run."
From here, when I click the "View All Tests" button, it takes me to the runner tool. There I see the indication that something is still running in the background. I tried waiting for more than 10 minutes but nothing happens until I click on the "Stop" action.
How do I debug this? Can I see what is happening via any log etc?
There could even be something wrong with my website as well, but without any log information, I'm unable to proceed further. Any help is appreciated.
To provide more context, I don't think this is a timeout based issue as if that were the case, cypress did report to me about this and stopped. I then increased the timeout.
My spec file
describe('My first test', function() {
it('Visits home page', function() {
cy.visit('https://mywebsite.com:5800', {timeout: 400000}, {pageLoadTimeout: 400000}, {defaultCommandTimeout: 400000})
cy.get('#USERNAME').type('myusername')
cy.get('#PASSWORD').type('mypassword')
cy.get('#loginbutton').click()
cy.get('#SOMELEMENT_WHERE_I_TYPE_A_UNIQUE_NUMBER').type('8056')
cy.get('#loginbutton').click()
cy.get('#loginbutton').click()
})
})
Thanks.
If you run DEBUG=cypress:* cypress open from the terminal when initially opening Cypress, there will be more debug log information printed there while you run your tests.
Also, it's always a good idea to search the issues for the project to see if anyone else has had this happen.
For some reason, the Cypress automation gets into a state where it thinks that you have no spec file. All Cypress does to determine this is to see if there is a location.hash defined on the main window -> where it usually says https://localhost:2020/__/#tests/integration/my_spec.js.
Likely this is due to security mechanisms in the app that prevent your application from being run within an iframe (which is how Cypress runs all applications under test). Maybe in your application code it is something like:
if (top !== self) {
top.location.href = self.location.href;
}
You can simply disable these checks while testing or in Cypress you can add to your test file (or a support file to have it work on every test file):
Cypress.on('window:before:load', (win) => {
Object.defineProperty(win, 'self', {
get: () => {
return window.top
}
})
})
I had the same issue. Usually this is related to the page moving out of the parent and can be solved by invoking the attribute and changing it to the current page.
cy.get('.approved-content .no-auto-submit').invoke('attr', 'target', '_self');

Morbo server works only after constant refresh

I am developing a web application with Mojolicious. The morbo development server is a wonderful thing that works great, but once I start returning complicated hashes on the stack and then rendering a webpage, the morbo server will start to act funny. In my browser, if I navigate to one of those webpages that use a complicated hash, the browser will tell me that the connection has been reset. I have to refresh about 10-12 times before the page will load.
For example:
The code below shows one of my app controllers. It simply gets a json object from an AJAX request, and then returns a different json object. It works fine, except that the browser demands to be refreshed a thousand times before it will load.
package MyApp::Controller::Library;
use Mojo::Base 'Mojolicious::Controller';
use Mojo::Asset::File;
use MyApp::Model::Generate;
use MyApp::Model::Database;
use MyApp::Model::IpDatabase;
use Mojo::JSON qw(decode_json);
# Receives a json object from an AJAX request and
# sends the necessary information back to be
# displayed in a table.
sub list_ajax_catch {
my $self = shift;
my $json = $self->param('data');
my $input = decode_json $json;
$self->render(
json => {
"Object A" => {
"name" => "Object A's Name",
"description" => "A Description for Object A",
"height" => "10",
"width" => "5",
}
}
);
}
1;
The problem is not limited to this instance. It seems that anytime there is a lot of processing on the server, the browser has troubles resetting. It doesn't matter what browser, I've tried Chrome, IE, Firefox, and others (on multiple computers). It doesn't matter if I'm not even sending or receiving data back and forth from the html to the app. All that seems to trigger it is if there is any amount of processing in my web app that is more than just rendering templates, BUT if I am running Hypnotoad, everything is fine.
This example is not one that requires a lot of processing, but it does cause the browser to reset, and as you can see, it shouldn't take long to run or freeze anything up. I thought the problem was a timeout issue, but by default, timeout doesn't happen until after 15 seconds, so it can't be that.
I have figured out the problem! This has been an issue for me for over a month now and I am so glad that it is working again. My problem was that when I started the morbo development server, I used the following command:
morbo -w ~/web_dev/my_app script/my_app
The -w allows me to watch a directory for changes so that I don't have to restart the app each time I changed some of my JavaScript files. My problem was that the directory I watched also contained my log files. So each time I went to my webpage, the logs would change and the server would restart.

How to handle every request in a Firefox extension?

I'm trying to capture and handle every single request a web page, or a plugin in it is about to make.
For example, if you open the console, and enable Net logging, when a HTTP request is about to be sent, console shows it there.
I want to capture every link and call my function even when a video is loaded by flash player (which is logged in console also, if it is http).
Can anyone guide me what I should do, or where I should get started?
Edit: I want to be able to cancel the request and handle it my way if needed.
You can use the Jetpack SDK to get most of what you need, I believe. If you register to system events and listen for http-on-modify-request, you can use the nsIHttpChannel methods to modify the response and request
let { Ci } = require('chrome');
let { on } = require('sdk/system/events');
let { newURI } = require('sdk/url/utils');
on('http-on-modify-request', function ({subject, type, data}) {
if (/google/.test(subject.URI.spec)) {
subject.QueryInterface(Ci.nsIHttpChannel);
subject.redirectTo(newURI('http://mozilla.org'));
}
});
Additional info, "Intercepting Page Loads"
non sdk version and with much much more control and detail:
this allows you too look at the flags so you can only watch LOAD_DOCUMENT_URI which is frames and main window. main window is always LOAD_INITIAL_DOCUMENT_URI
https://github.com/Noitidart/demo-on-http-examine
https://github.com/Noitidart/demo-nsITraceableChannel - in this one you can see the source before it is parsed by the browser
in these examples you see how to get the contentWindow and browserWindow from the subject as well, you can apply this to sdk example, just use the "subject"
also i prefer to use http-on-examine-response, even in sdk version. because otherwise you will see all the pages it redirects FROM, not the final redirect TO. say a url blah.com redirects you to blah.com/1 and then blah.com/2
only blah.com/2 has a document, so on modify you see blah.com and blah.com/1, they will have flags LOAD_REPLACE, typically they redirect right away so the document never shows, if it is a timed redirect you will see the document and will also see LOAD_INITIAL_DOCUMENT_URI flag, im guessing i havent experienced it myself

Resources