Matcher error: received value must not be null nor undefined - javascript

I am using expect in typescript to write an assertion while writing a Then step definition using typescript in in playwright
I have assigned an the class on this url https://www.gov.uk/help/accessibility-statement to confirm I can see accessibility statement when I land on the page.
I then get an undefined error when I run my tests.
Code written:-
import expect from "expect";
Then("I expect to be on the accessibility page", async function(
this: OurWorld
)
{
const {page} = this;
// eslint-disable-next-line no-debugger
const headMessage =await page?.$(".gem-c-title__text.govuk-heading-xl")
console.log(headMessage)
expect (headMessage).toContainEqual(("Accessibility statement")
);
});
I would like to check that the accessibility icon on the accessibility page contains the text accessibility.
The error I am getting back is this:-
× Then I expect to be on the accessibility page # step-definitions\feature.step-definitions.ts:28
Error: expect(received).toContainEqual(expected) // deep equality
Matcher error: received value must not be null nor undefined
Thank you for your help

Related

Cypress - nested function instead of using while loop

I spotted that when I'm using while loop, cypress does not work, so instead of while loop I found this kind of solution:
const functionName = () => {
if ( a != b ) {
this.functionName();
} else {
cy.get(".selector").click()
}
};
This block of code (typescript) works really well, but 'this' is highlighted in red and the message appears: "Object is possibly 'undefined'."
Any idea how can I to get rid off this error?
Assuming it's a typescript error, add the Non-null assertion operator
// Compiled with --strictNullChecks
function validateEntity(e?: Entity) {
// Throw exception if e is null or invalid entity
}
function processEntity(e?: Entity) {
validateEntity(e);
let s = e!.name; // Assert that e is non-null and access name
}
For reference, How to suppress "error TS2533: Object is possibly 'null' or 'undefined'" answers the same question.
You probably don't need the this. prefix at all, since the function is defined on the current scope (not a class method).

How Do I Suppress A Specific Error In Jest Tests

I'm trying to suppress a specific error in our Jest tests as we've got plans to resolve it later, but until then we don't want these errors potentially hiding any true errors.
The errors occur across the codebase so my current strategy is to rewire the console.error function in our jest setup file.
I've taken two different attempts, both almost working however now when they report a true error - they're adding a new line onto the error trace.
Attempt 1:
const originalError = console.error.bind(console.error);
jest.spyOn(global.console, 'error').mockImplementation((message) => {
if (
!message
.toString()
.includes(
'Warning: An update to SettingsPanel inside a test was not wrapped in act'
)
) {
originalError(message);
}
});
Attempt 2:
const { error } = console;
global.console = {
...console,
error: (errorMessage) =>
!errorMessage
.toString()
.includes(
'Warning: An update to SettingsPanel inside a test was not wrapped in act'
) && error(errorMessage),
};
Both of these will log a valid error - i.e. 'Warning: Each child in a list should have a unique "key"' - However instead of pointing me to the code with the issue it points me back here
console.error
Warning: Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/docs/lists-and-keys.html#keys for more information.%s
18 | .includes(
19 | 'Warning: An update to SettingsPanel inside a test was not wrapped in act'
> 20 | ) && error(errorMessage),
| ^
21 | };
at Object.error (jest.setup.js:20:12)
at printWarning (node_modules/react/cjs/react.development.js:315:30)
at error (node_modules/react/cjs/react.development.js:287:5)
at validateExplicitKey (node_modules/react/cjs/react.development.js:1630:5)
at validateChildKeys (node_modules/react/cjs/react.development.js:1656:9)
at Object.createElementWithValidation [as createElement] (node_modules/react/cjs/react.development.js:1806:7)
at src/js/components/SettingsPanel/DataListAutocompleter/DataListAutocompleter.tsx:85:13
I've searched and searched and all I can find are questions about silencing all errors or silencing a specific test - nothing I've found has helped me solve this.
Use failOnConsole in your setupFilesAfterEnv configuration.
You can configure this to silence some errors, and fail on others:
import failOnConsole from 'jest-fail-on-console'
failOnConsole({
silenceMessage: (errorMessage) => {
if (/'Warning: An update to .*? inside a test was not wrapped in act/.test(errorMessage)) {
return true
}
return false
},
})
This should silence ALL instances of that error. Everything else will go through, it will give you more lines, but should still preserve the original source of the error, underneath the line it adds.

JS ERROR: Error: Expected an object of type GCancellable for argument 'cancellable' but got type string

I'm trying to follow this tutorial.
Basically, I want to create my custom function that creates a folder if it not exists.
var makeDir = (path) => {
const file = Gio.file_new_for_path(path);
if (file.query_exists(path)) {
print(`Dir already exists ${path}`);
return;
}
print(`My Path: ${path}`);
// file.make_directory(path);
};
When I run this code I'm receiving an error:
Gjs-CRITICAL **: 17:35:17.161: JS ERROR: Error: Expected an object of type GCancellable for argument 'cancellable' but got type string
In the documentation I see that GCancellable is optional. So I have no idea why my code does not work. Haw can I make it work?
In the C documentation, "optional" means something else than it usually does in JS: it means it's optional to pass a real pointer as that argument, and you may also pass NULL.
The error message is complaining about a string because query_exists() does not take a path string argument. Check the JS documentation for the list of arguments accepted in JS: you should call file.query_exists(null).

Not counting DOM elements in React site with Cypress?

I can't count the number of DOM elements on a site written in React.
/// <reference types="cypress" />
context('Checking all components', () => {
beforeEach(() => {
cy.visit('https://news-israel.com');
});
it('Checking posts', () => {
cy.get('.posts-wrapper').find('a').should('exist');
cy.get('.posts-wrapper').find('a').its('length').should('be.gte', 100);
});
});
In this case, it doesn't find the "a" tags because React rendering them asynchronously and dynamically.
The "post-wrapper" class finds, followed by an exception:
The following error originated from your application code, not from Cypress.
Cannot read property 'substr' of undefined
When Cypress detects uncaught errors originating from your application it will automatically fail the current test.
How to correctly count the number of elements in this case, so that you can "wait for the elements"?
The site I'm testing is in production - https://news-israel.com
The error is coming from the app itself, and ultimately should be fixed in the app source.
But see this note in the log
This behavior is configurable, and you can choose to turn this off by listening to the uncaught:exception event.
This links to an event handler you can use to debug. Add this to the top of the test to suppress the test failing when the error occurs.
Cypress.on('uncaught:exception', (err, runnable) => {
// returning false here prevents Cypress from
// failing the test
return false
})
Now the test works, provide you use the correct class posts-wrapper not post-wrapper.
If you are able to fix the source, the error comes from the react-typed library, which is used in BreakingNews.js at line 75
<Typed
strings={posts}
typeSpeed={15}
backSpeed={10}
backDelay={5000}
loop
/>
the posts variable is initially undefined, so you need a fallback value, e.g strings={posts || []}
To globally Handle Uncaught exceptions, Go to cypress/support/index.js and write:
Cypress.on('uncaught:exception', (err, runnable) => {
return false
})
Now to count the number of elements you do it via each() or by using Cypress.$
Using each():
cy.get('div.post-title').each((ele, list) => {}).then((list) => {
cy.log(list.length)
})
Using Cypress.$
cy.get('div').find('.post-title').then(ele => {
cy.log(Cypress.$(ele).length)
})
OR, As suggested by #Hiram
cy.get('div.post-title').then(ele => {
cy.log(Cypress.$(ele).length)
})

Ramda: access input object's properties inside R.ifElse() function call

I have this existing function:
const inferProcessingError = R.ifElse(
R.propEq('conversionJobStatus', 3),
R.always('Last Process failed with error; please contact DevOps'),
R.always(null)
);
which is called like this:
const msg = inferProcessingError(jobStruct || {});
with this jobStruct:
{"id":9,"mediaGroupId":1000000,"conversionJobStatus":3,
"errorDetails": {
"Cause": {
"errorMessage": "MediaConvert Job Failed with ERROR status: ERROR Video codec [indeo4] is not a supported input video codec",
},
"Error": "Error",
}
}
and I need to create an error message string which includes the data from the Cause.errorMessage element.
This would be dead simple with a native JavaScript function, but I'm learning Ramda and want to just modify the existing code to include in the error message.
An R.prop('Cause')['errorMessage'] could work except that I can't figure out how to reference the jobStruct that was passed in to the inferProcessingError statement.
I can see that the R.ifElse and subsequent Ramda functions are able to get that reference, but when I embed an R.prop('Cause') in the error message string, it resolves to a function and not the value of the Cause element because it seems to be waiting for the data structure.
So...how do I gain access to the jobStruct reference? (arguments is not defined here).
UPDATE:
I can get this to work by referencing the original jobStruct as in R.Prop('ErrorDetails', jobStruct)['Cause']['errorMessage'] but that seems rather kludgy to me...
BUT if the call to inferProcessingError is actually inside a map statement and references an element in a larger structure, then the map index is not available to reference the data structure for the R.prop.
Perhaps you could use the pipe and path methods to achieve this "the ramda way".
Begin by using ramda's path() function to extract the nested errorMessage value from the input jobStruct object. Next, enclose that in a pipe() that transforms the extracted message into a string formatted with a custom error prefix:
const incCount = R.ifElse(
R.propEq('conversionJobStatus', 3),
/* Evaluate this pipe if the error case is satisfied */
R.pipe(
/* Path to extract message from input object */
R.path(["errorDetails", "Cause", "errorMessage"]),
/* Prefix string to extracted error message */
R.concat('Custom error prefix:')),
R.always('')
);
incCount({"id":9,"mediaGroupId":1000000,"conversionJobStatus":3,
"errorDetails": {
"Cause": {
"errorMessage": "MediaConvert Job Failed with ERROR etc etc",
},
"Error": "Error",
}
});
Here's a working example - hope that helps!
Update
Thanks to #customcommander for the suggestion to use concat for the string prefix, as well as returning an empty string value for the second branch

Categories