Cypress Command log truncate - javascript

Is it possible to truncate the Command Log for the assertion methods?
I have such test
cy.request('/').its('body').should('contain' 'somestring');
The body contains the whole page HTML as a string which results in massive pollution in the Command log in cypress which leads to memory issues. If I would like to do more assertions it will crash cypress.
How can truncate the assert log so it doesn't load the whole body in the assertion Command Log
I've tried saving the HTML string to file and reading it so I could make an assertion like on a normal page but currently, it seems not possible in Cypress to load the local file.
Cherrio is also a thing I could potentially use to retrieve data from that HTML string but I would like to avoid using it.

The trick to suppressing the verbiage in the log is to pre-test the condition,
cy.request('http://example.com')
.its('body')
.then(body => body.includes('Example')) // map to a boolean
.should(result => expect(result, 'Body contains "Example"').to.be.true)
results in
assert Body contains "Example": expected true to be true

As per documentation here, you can pass { log: false } to request.
Check the options section on above documentation

Related

How to error handle in cypress for element not found

The below block successfully executes when tr is found, but sometimes it will be empty and no tr. How to handle the exception if tr not found?
cy.get('tbody.ant-table-tbody tr').then((rows) => {
// success
});
There is no catch block chained here.
cy.get() will always fail if it cannot find the element (unless you run cy.get('foo').should('not.exist'), but that can't be used in combination with if/else.)
You can instead use JQuery in combination with Cypress to check for an element's existence without failing a test. In this case, we'll yield the result from the parent element, and search it with JQuery.
cy.get('tbody.ant-table-tbody').then(($parent) => {
if ($parent.find('tr').length) { // check if the length is > 0
// Code to run if tr is found
} else {
// Code to run if tr is not found
}
});
All of that being said, I would push back on needing to use something like this. Tests should be deterministic, and you should know before the test runs if tr exists or not. Consider the ways that you can pre-determine before the test runs (maybe seeding a database, or intercepting a network request). Also consider, what happens if tr never exists -- that functionality is never being tested. Or, if tr always exists, then the functionality of when it doesn't exist is never being tested.
There is an add-on package cypress-if written by former lead engineer at Cypress that addressed this problem.
The syntax is simple, just chain .if() and eveything after it only runs if the element is found.
cy.get('tbody.ant-table-tbody tr')
.if() // checks for 4 seconds
.then((rows) => {
// success
})
.else()
.then(() => {
//no rows
})
.finally(() => {
// either way
})
It will suppress the error that usually occurs when the element is missing.
It will use Cypress retry for asynchronous element loading, will will not happen if you use the jQuery method.
Don't do this if rows are fetched asynchronously
cy.get('tbody.ant-table-tbody').then(($parent) => {
// This will evaluate immediately and fail if the row is still loading
if ($parent.find('tr').length) {
...
But cypress-if is broken in Cypress v12
Cypress v12 split cypress commands into "commands" and "queries" (cy.get() is a query) and blocked overwriting of queries. This breaks a whole lot of prior code, including cypress-if.
Expect the change to be reversed before long.
Please see issue Can we please overwrite query commands #25078

Whats the difference between toBeInTheDocument and getBy* in #testing-library/react

Is there a difference between
expect(screen.queryByText('<something>')).toBeInTheDocument();
And
screen.getByText('<something>');
(The specific getBy* and queryBy* operation are not relevant)
In react-testing-library?
getByText tries to find the node and throws an error when it is not able to find it. This will cause the test to fail immediately.
queryByText on the other hand will return null if it is unable to find the node.
Let's suppose you have text <something> in the component that was rendered, you can assert if it has been rendered or not.
If sure that the text has been rendered, then you can simply use getByText
expect(screen.getByText('<something>')).toBeInTheDocument();
and the test would pass.
If for the scenario the text did not render then the above assertion will thrown an error and fail the test case.
In such cases queryByText text makes the most sense
When has not been rendered
expect(screen.getByText('<something>')).not.toBeInTheDocument(); // throws an error
expect(screen.queryByText('<something>')).not.toBeInTheDocument(); // asserts as true
Output comparison

Firestore SDK cannot mock DocumentSnapshot

So I am trying to create a unit test for a firestore trigger, triggered by an onCreate event. The firebase documentation said to do this as so: Firebase Unit Testing Background Functions
I copy the documentation pretty closely:
const snapshot = test.firestore.makeDocumentSnapshot(
{owner: 'testUserA', text: 'response from test user a'},
'users/testUserA/questions/testQuestion/responses/testResponse'
);
This line gives the error:
UnhandledPromiseRejectionWarning: SyntaxError: Unexpected token u in JSON at position 0
At first I thought it might have to do with the refPath because it starts with u, but after changing it, the error is identical, so I assume it has to do with the first parameter, which seems like correct json, but apparently not. I'm kind of stumped.
Any ideas? Thanks!
Do you have test.cleanup() in any other testing cases before you use test.firestore.makeDocumentSnapshot()? If any, remove them and run the test again

ERROR: 'console is not defined. [no-undef] - Brackets

I've installed brackets and currently playing around with variables and functions. All the outputs work fine in the console, however I keep getting this error in the editor.
How do I go about fixing this?
The no-undef rule looks out for undefined variable, without any initial assumption on the environment and the global variables (console for instance).
You can specify that you are in an environment where console indeed exists, by adding browser and/or node envs in your .eslintrc:
env: {
browser: true,
node: true,
},
More info in the rule doc
just to have comment:
/*global console*/
as the first line of your .js file, and then have:
// eslint-disable-line no-console
at the line of the console.log("");
this will make the error go away!
Since you have it as a Capitol C, I would guess that the editor thinks you're looking for a function or class. Try lowering it from Console.log() to console.log("john won...") and see if that works.
I assume it's coming from no-console rule, which disallows calls to methods of the console object.
In JavaScript that is designed to be executed in the browser, it’s
considered a best practice to avoid using methods on console. Such
messages are considered to be for debugging purposes and therefore not
suitable to ship to the client. In general, calls using console should
be stripped before being pushed to production.
Examples of correct code for this rule:
/*eslint no-console: "error"*/
// custom console Console.log("Hello world!");
As a solution, you can add this to your set of rules in .eslintrc
rules: {
'no-console': 'off'
}
This one was driving me crazy as well. You can edit Brackets' config JSON. It will remove the error icon from the left gutter:
{
"brackets-eslint.gutterMarks": false
}
Reference: https://github.com/brackets-userland/brackets-eslint/blob/master/README.md
add 'no-console' in rules object is inactive
I think you should write "console.log" instead of "Console.log". It should be lowecase.
This might seem like a special case, but deleting and recreating the .eslintrc file fixed this issue for me.

`waitForEnabled()` says "selector needs to be typeof `string`" even though string was passed

I was originally using the mocha command line tool to run my tests and they were working fine. I switched to using the wdio command to run my tests. My tests now throw an error with this line of code:
browser.waitForEnabled('#div_id');
With this error:
Promise was rejected with the following reason: Error: selector needs to be typeof `string`
running chrome
Error: Promise was rejected with the following reason: Error: selector needs to be typeof `string`
at elements() - isEnabled.js:18:17
at isEnabled() - waitForEnabled.js:37:22
This was working fine until I started using wdio (specifically I run wdio --spec path/to/file.js). I've run the typeof function on the selector in question and verified that it is, in fact, a string.
The div in question looks like this:
<div class="highlight" id="div_id">
A fair bit of content goes here.
</div>
Why am I seeing this error? How do I fix it?
waitForEnabled() documentation => http://webdriver.io/api/utility/waitForEnabled.html
wdio documentation => http://webdriver.io/guide/testrunner/gettingstarted.html
Update:
I've tried adding a timeout to the waitForEnabled() function. Since I've done so, it sometimes fails, and sometimes does not. More often it fails though.
I'm not marking this as the answer because I have no idea why it works. But passing in all of the optional params to waitForEnabled() makes it work just fine.
As in:
waitForEnabled('#div_id'); Fails. Wheras:
waitForEnabled('#div_id', 99999, false); works without errors.
The fact that you're passing milliseconds & the false option should not make the test pass.
I'd suggest using some of the other waitFor commands, like waitForVisible() or waitForExist(), because I'm assuming this is what you really want from the code example you gave above. The waitForEnabled() command waits for a field that had a disabled html attribute, to not have it anymore. You can read more on that here: https://www.w3schools.com/tags/att_disabled.asp.

Categories

Resources