How Do I Suppress A Specific Error In Jest Tests - javascript

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.

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).

Matcher error: received value must not be null nor undefined

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

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)
})

vue.esm.js:649 [Vue warn]: Error in nextTick: "TypeError: Cannot convert object to primitive value" vue

I'm getting the following warning [Vue warn]: Error in nextTick: "TypeError: Cannot convert object to primitive value" followed by an error TypeError: Cannot convert object to primitive value.
This happens upon setting an object in the store. The data is set in the store correctly, the problem appear to be happening in the renderization of the page after the nextTick is happening.
The console log for the error shows:
at baseSetAttr (vue.esm.js:6811)
at setAttr (vue.esm.js:6786)
at Array.updateAttrs (vue.esm.js:6740)
at patchVnode (vue.esm.js:6312)
at updateChildren (vue.esm.js:6188)
On the file vue.esm.js:6811 I get the following:
function baseSetAttr(el, key, value) {
if (isFalsyAttrValue(value)) {
el.removeAttribute(key);
} else {
// #7138: IE10 & 11 fires input event when setting placeholder on
// <textarea>... block the first input event and remove the blocker
// immediately.
/* istanbul ignore if */
if (isIE && !isIE9 && el.tagName === 'TEXTAREA' && key === 'placeholder' && value !== '' && !el.__ieph) {
var blocker = function (e) {
e.stopImmediatePropagation();
el.removeEventListener('input', blocker);
};
el.addEventListener('input', blocker); // $flow-disable-line
el.__ieph = true;
/* IE placeholder patched */
}
el.setAttribute(key, value); <--- The error happens here
}
}
I wish I could give more details to this question but I don't have any idea where or why this error is happening directly on my code. I have two pages using the same service, one render it correctly and the other happens this error. I have looked and made sure that both pages are exactly the same but this only happens in one
The answer will seem something extremely stupid but if anyone has an answer on why this happens I will gladly accept the answer.
The problem happens on this line of code on my implemented code:
<template #results="{ items, loading, sort, onSort, orderedHeaders, onColumnOrderChange }">
<order-summary :sort="sort"/>
The component order-summary doesn't have a prop sort. Upon removing of the prop sort everything works correctly.
<template #results="{ items, loading, sort, onSort, orderedHeaders, onColumnOrderChange }">
<order-summary/>
If anyone would have an explanation on why this happens I would gladly accept the answer
I also encountered the same problem. Although I don’t know what caused the problem, I can use
JSON.parse(JSON.stringify(***))
to solved
The reason is this: when parent component pass a prop to child component, and when child component did not receive the prop by registering prop filed, vue will think call prop.toString and put the value to the child's DOM element.
sth like this:
<div sort="[object Object]"></div>
and if the sort prop does have toString method, it will throw the Error you encoutered.
eg:
var a = Object.create(null);
var b = `${a}`, // TypeError: Cannot convert object to primitive value

Can't find source of: `uncaught syntaxerror` (only occurs in cypress)

Looking for suggestions on how to pinpoint the actual source of the invalid/unexpected token.
I'm running tests with cypress, and most of the time (though not consistently), I'm getting this error from all my tests.
Uncaught SyntaxError: Invalid or unexpected token
This error originated from your application code, not from Cypress.
When Cypress detects uncaught errors originating from your application it will automatically fail the current test.
This behavior is configurable, and you can choose to turn this off by listening to the 'uncaught:exception' event.
https://on.cypress.io/uncaught-exception-from-application
So let's be clear; I do understand that it's an issue with my application code, rather than my test code. My issue is that I have yet to see anything pointing to an actual location of the syntax error. Furthermore, I run the app in chrome 72 (not through cypress) and I have no issue. There only seems to be an issue when I run the app through cypress (also using chrome 72 because I'm using --browser chrome when i run the cypress specs).
I've added fail, and uncaught:exception handlers to my tests to catch the output, though I still can't find anything to direct me to where the actual source of the error is.
by breaking in the uncaught:exception handler, there are two args passed,
1) the error (same as above); 2) the mocha(i think) runnable:
Hook {title: ""before all" hook", fn: ƒ, body: "function () {↵ var _this = this;↵↵ debugger;… cy.visit("/#/account-management");↵ });↵ }", async: 0, sync: true, …}
$events: {error: Array(1)}
async: 0
body: "function () {↵ var _this = this;↵↵ debugger;↵ cy.on('fail', event_handler_functions_1.failHandler.bind(this));↵ cy.on('uncaught:exception', function (e, r) {↵ console.log(e, r);↵ debugger;↵ });↵ cy.fixture(Cypress.env("environmentSettings")).then(function (fixture) {↵ _this.environmentData = environmentData = fixture;↵ cy.launchApp(environmentData.baseUrl, environmentData.username, environmentData.password↵ /*, 300000*/↵ );↵ cy.visit("/#/account-management");↵ });↵ }"
callback: ƒ done(err)
ctx: Context {currentTest: Test, _runnable: Hook, test: Hook, environmentData: {…}}
fn: ƒ ()
hookId: "h1"
hookName: "before all"
id: "r3"
parent: Suite {title: "Account Management", ctx: Context, suites: Array(0), tests: Array(3), pending: false, …}
pending: false
sync: true
timedOut: false
timer: null
title: ""before all" hook"
type: "hook"
_currentRetry: 0
_enableTimeouts: false
_retries: -1
_slow: 75
_timeout: 4000
_trace: Error: done() called multiple times at Hook.Runnable (https://localhost:44399/__cypress/runner/cypress_runner.js:30161:17) at new Hook (https://localhost:44399/__cypress/runner/cypress_runner.js:26593:12) at Suite.beforeAll (https://localhost:44399/__cypress/runner/cypress_runner.js:31573:14) at before (https://localhost:44399/__cypress/runner/cypress_runner.js:26770:17) at context.describe.context.context (https://localhost:44399/__cypress/runner/cypress_runner.js:26666:10)
__proto__: Runnable
I've stepped through before() in my test, with "Pause on Exceptions" enabled in the chrome debugger. Nothing errors until after I've stepped through everything in before() and have to then "Resume script execution".
Note, I don't have a beforeAll() hook in my test, just a before().
I haven't made an recent changes which use unusual syntax (so far as I can tell), and I haven't ran the test suite in my local environment for a few weeks, so there are many changes - too many for me to feel like sifting through them one by one would be worthwhile.
here's the test from that error instance for reference, though they're all having the same issue.
import { failHandler } from "..\\..\\support\\event-handler-functions"
describe('Account Management', function () {
var environmentData: CypressTypings.EnvrionmentSettings;
before(function () {
debugger;
cy.on('fail', failHandler.bind(this))
cy.on('uncaught:exception', (e, r) => {console.log(e, r); debugger;})
cy.fixture(Cypress.env("environmentSettings")).then((fixture) => {
(<any>this).environmentData = environmentData = fixture
cy.launchApp(environmentData.baseUrl, environmentData.username, environmentData.password/*, 300000*/);
cy.visit("/#/account-management");
});
})
beforeEach(() => {
Cypress.Cookies.preserveOnce(environmentData.cookieName)
})
it('Loads Governments', function () {
cy.get("[data-cy=government-panel]", { timeout: 20000 }).should("have.length.gte", 1);
})
it('Users Page Loads', function () {
cy.get("[data-cy=government-panel]").first().find(".fa-users").click();
cy.get("tbody", { timeout: 20000 }).find("tr").should("have.have.length.greaterThan", 0);
cy.get("[data-cy=return-to-organization-button]").click();
cy.get("[data-cy=government-panel]").should("exist");
})
it('Service Area Page Loads', function () {
cy.get("[data-cy=government-panel]").first().find(".fa-globe").click();
cy.get("tbody", { timeout: 20000 }).find("tr").should("have.have.length.greaterThan", 0);
cy.get("[data-cy=return-to-organization-button]").click();
cy.get("[data-cy=government-panel]").should("exist");
})
})
Also worth noting: the launchApp() step actually occurs - the app is logged in, and then it appears to be as the app is loading in, that the syntax error is raised and the visit() step is never actually executed.
If someone else runs into this in the future, mine was down to trying to load a non existent JS file(from my index page).
Cypress seems to hide the error, so logging it helped;
Cypress.on('uncaught:exception', (err, runnable) => {
console.log(err);
return false;
})
I trimmed down our npm packages, suspecting that maybe a package which was added might have introduced the SyntaxError.
I removed about 1/4 of our npm packages (which was long overdue anyways), and cleaned up our dependencies. After all that, the Uncaught SyntaxError went away.
I suspect it was one of the following packages which introduced the error, though I can't say definitively because I never actually pinpointed the source of the error.
Packages which I ended removing (some of which we likely updated recently):
#types/plotly.js
aurelia-animator-css
#types/jest
#types/node
#types/pikaday
ajv
d3
jest
jest-cli
jquery-sparkline
nps-utils
opn
protractor
ts-jest
ts-node
uglify-js
vinyl-fs
wait-on

Categories