Yarn test fails because of 'createEvent' not found (create-react-app) - reactjs

I've a simple react project created with create-react-app. Just after created the project the yarn test command worked fine, then I started to add some actual react code and I eventually got this error, just after the test is executed:
PASS src/test/App.test.js
✓ renders without crashing (28ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 0.729s, estimated 1s
Ran all test suites related to changed files.
Watch Usage
› Press a to run all tests.
› Press p to filter by a filename regex pattern.
› Press t to filter by a test name regex pattern.
› Press q to quit watch mode.
› Press Enter to trigger a test run.
/Users/mpegorar/Development/SpringApps/fluxy_frontend/node_modules/react-scripts/scripts/test.js:20
throw err;
^
TypeError: Cannot read property 'createEvent' of undefined
at Object.invokeGuardedCallbackDev (/Users/mpegorar/Development/SpringApps/fluxy_frontend/node_modules/react-dom/cjs/react-dom.development.js:577:25)
at invokeGuardedCallback (/Users/mpegorar/Development/SpringApps/fluxy_frontend/node_modules/react-dom/cjs/react-dom.development.js:436:27)
at renderRoot (/Users/mpegorar/Development/SpringApps/fluxy_frontend/node_modules/react-dom/cjs/react-dom.development.js:10386:7)
at performWorkOnRoot (/Users/mpegorar/Development/SpringApps/fluxy_frontend/node_modules/react-dom/cjs/react-dom.development.js:11000:24)
at performWork (/Users/mpegorar/Development/SpringApps/fluxy_frontend/node_modules/react-dom/cjs/react-dom.development.js:10952:7)
at requestWork (/Users/mpegorar/Development/SpringApps/fluxy_frontend/node_modules/react-dom/cjs/react-dom.development.js:10861:7)
at scheduleWorkImpl (/Users/mpegorar/Development/SpringApps/fluxy_frontend/node_modules/react-dom/cjs/react-dom.development.js:10744:11)
at scheduleWork (/Users/mpegorar/Development/SpringApps/fluxy_frontend/node_modules/react-dom/cjs/react-dom.development.js:10706:12)
at Object.enqueueSetState (/Users/mpegorar/Development/SpringApps/fluxy_frontend/node_modules/react-dom/cjs/react-dom.development.js:6204:7)
at App.Object.<anonymous>.Component.setState (/Users/mpegorar/Development/SpringApps/fluxy_frontend/node_modules/react/cjs/react.development.js:226:16)
at then.then.jsonData (/Users/mpegorar/Development/SpringApps/fluxy_frontend/src/components/App.js:25:9)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
The test is actually executed and it changes if I put some error inside, but the tool exit while usually it would stay up and running continuing executing tests based on the code.
The line in my code that seems to cause this error is the set state here described:
componentDidMount() {
const headers = new Headers()
headers.append('Content-Type', 'application/hal+json')
fetch(`${url}/listEnvironmentResources`, { headers }).then(
function(response){
return response.json();
}
).then(jsonData => {
this.setState({environmentRecords: jsonData._embedded.environmentRecordResources});
});
}
Previously the test was not working because of this error, fixed as for the accepted answer.
The only reference I found about the error is this, but it didn't solve my problem.
Any idea how can I fix this? Looks like some missing dependency but can't find which one.

Related

React Native : Invariant Violation: `new NativeEventEmitter()` requires a non-null argument

I am writing jest test case for a particular file, the file has NativeModule import in it.
While running the test case, I am getting the following error:
● Test suite failed to run
Invariant Violation: `new NativeEventEmitter()` requires a non-null argument.
at invariant (node_modules/invariant/invariant.js:40:15)
at new NativeEventEmitter (node_modules/react-native/Libraries/EventEmitter/NativeEventEmitter.js:45:7)
at Object.<anonymous> (node_modules/react-native-quantum-metric-library/index.js:1:322)
After googling the above error, I did few changes by adding the following code inside the test file.
jest.mock('react-native/Libraries/EventEmitter/NativeEventEmitter');
After adding the above line then I got the following error:
Test suite failed to run
TypeError: Cannot set properties of undefined (setting 'eventType')
at Object.<anonymous> (node_modules/react-native-quantum-metric-library/index.js:1:367)
After googling again, I modified the above code with the following code.
jest.mock('react-native/Libraries/EventEmitter/NativeEventEmitter.js', () => {
const {EventEmitter} = require('events');
return EventEmitter;
});
After above modification I am getting the below error.
● Test suite failed to run
TypeError: _reactNative.NativeEventEmitter is not a constructor
at Object.<anonymous> (node_modules/react-native-quantum-metric-library/index.js:1:322)
Can anyone please help me to resolve the above issue.

How do I find where 'given node is not an Element, the node type is: string' error occurred from stack trace? (react/JS)

I'm writing a react app as a practice and I get the following error on several components, however I can't see that it tells me where it comes from? It doesn't prevent tests (jest/react testing library) passing or indeed build (WIP app is successfully deployed to netlify). Nevertheless, I'd like to track it down if only for understanding:
Error: The given node is not an Element, the node type is: string.
at getWindowFromNode (/Users/learning/Documents/projects/mol-bio-tools/node_modules/#testing-library/dom/dist/helpers.js:58:11)
at hasPointerEvents (/Users/learning/Documents/projects/mol-bio-tools/node_modules/#testing-library/user-event/dist/utils/misc/hasPointerEvents.js:11:49)
at click (/Users/learning/Documents/projects/mol-bio-tools/node_modules/#testing-library/user-event/dist/click.js:116:63)
at typeImplementation (/Users/learning/Documents/projects/mol-bio-tools/node_modules/#testing-library/user-event/dist/type/typeImplementation.js:24:36)
at Object.type (/Users/learning/Documents/projects/mol-bio-tools/node_modules/#testing-library/user-event/dist/type/index.js:27:60)
at Object.<anonymous> (/Users/learning/Documents/projects/mol-bio-tools/src/__tests__/transcribe.test.js:33:15)
at Promise.then.completed (/Users/learning/Documents/projects/mol-bio-tools/node_modules/jest-circus/build/utils.js:391:28)
at new Promise (<anonymous>)
at callAsyncCircusFn (/Users/learning/Documents/projects/mol-bio-tools/node_modules/jest-circus/build/utils.js:316:10)
at _callCircusTest (/Users/learning/Documents/projects/mol-bio-tools/node_modules/jest-circus/build/run.js:218:40)
at processTicksAndRejections (node:internal/process/task_queues:95:5)
at _runTest (/Users/learning/Documents/projects/mol-bio-tools/node_modules/jest-circus/build/run.js:155:3)
at _runTestsForDescribeBlock (/Users/learning/Documents/projects/mol-bio-tools/node_modules/jest-circus/build/run.js:66:9)
at _runTestsForDescribeBlock (/Users/learning/Documents/projects/mol-bio-tools/node_modules/jest-circus/build/run.js:60:9)
at run (/Users/learning/Documents/projects/mol-bio-tools/node_modules/jest-circus/build/run.js:25:3)
at runAndTransformResultsToJestFormat (/Users/learning/Documents/projects/mol-bio-tools/node_modules/jest-circus/build/legacy-code-todo-rewrite/jestAdapterInit.js:170:21)
at jestAdapter (/Users/learning/Documents/projects/mol-bio-tools/node_modules/jest-circus/build/legacy-code-todo-rewrite/jestAdapter.js:82:19)
at runTestInternal (/Users/learning/Documents/projects/mol-bio-tools/node_modules/jest-runner/build/runTest.js:389:16)
at runTest (/Users/learning/Documents/projects/mol-bio-tools/node_modules/jest-runner/build/runTest.js:475:34)
at Object.worker (/Users/learning/Documents/projects/mol-bio-tools/node_modules/jest-runner/build/testWorker.js:133:12)
Current complete code is here and live app is here (again: WIP - I know various links/etc don't work yet).
Turns out if I actually read that trace it highlights an error in my test:
at Object.<anonymous> (/Users/learning/Documents/projects/mol-bio-tools/src/__tests__/transcribe.test.js:33:15)
Turns out I'd managed to use a hybrid of #testing-library/userevent v13.5 and v14 syntax, and there are breaking changes between the 2 versions. Updated to v14, updated syntax, all good.

Jest in Bitbucket pipelines: TypeError: Cannot read property 'body' of null

So I have some React component tests that are run on Bitbucket pipeline.
Locally they work fine, but in CI I get the following error:
FAIL src/tests/components/exercise-steps/performance-only/drag-and-drop/drag-and-drop-exercise.test.tsx (5.815 s)
● DragAndDropExerciseUnwrapped Tests › expect to render DragAndDropExercise component with fractions and text
TypeError: Cannot read property 'body' of null
99 | )?.innerHTML;
100 |
> 101 | const activeElement = document.getElementById(activeElementId);
| ^
102 | const correctionData =
103 | isStillOpen && item.correctionData ? null : item.correctionData;
104 | const isDisabled: boolean =
at getActiveElement (node_modules/react-dom/cjs/react-dom.development.js:1449:16)
at getActiveElementDeep (node_modules/react-dom/cjs/react-dom.development.js:7767:17)
at getSelectionInformation (node_modules/react-dom/cjs/react-dom.development.js:7800:21)
at prepareForCommit (node_modules/react-dom/cjs/react-dom.development.js:10163:26)
at commitRootImpl (node_modules/react-dom/cjs/react-dom.development.js:23085:29)
at unstable_runWithPriority (node_modules/react-dom/node_modules/scheduler/cjs/scheduler.development.js:468:12)
at runWithPriority$1 (node_modules/react-dom/cjs/react-dom.development.js:11276:10)
at commitRoot (node_modules/react-dom/cjs/react-dom.development.js:22990:3)
at performSyncWorkOnRoot (node_modules/react-dom/cjs/react-dom.development.js:22329:3)
at node_modules/react-dom/cjs/react-dom.development.js:11327:26
at unstable_runWithPriority (node_modules/react-dom/node_modules/scheduler/cjs/scheduler.development.js:468:12)
at runWithPriority$1 (node_modules/react-dom/cjs/react-dom.development.js:11276:10)
at flushSyncCallbackQueueImpl (node_modules/react-dom/cjs/react-dom.development.js:11322:9)
at flushSyncCallbackQueue (node_modules/react-dom/cjs/react-dom.development.js:11309:3)
at scheduleUpdateOnFiber (node_modules/react-dom/cjs/react-dom.development.js:21893:9)
at dispatchAction (node_modules/react-dom/cjs/react-dom.development.js:16139:5)
at src/components/correction-requests/correction-request-with-marking-area/correction-request-with-marking-area.component.tsx:101:9
at Array.map (<anonymous>)
at src/components/correction-requests/correction-request-with-marking-area/correction-request-with-marking-area.component.tsx:99:39
First I thought maybe it is trying to select the element by id while to component is no longer mounted.. Turns out the stack trace is the same, even when I comment that code - so it would point to the same line, which is a comment.
In general it seems kind of random when and if that error occurs - skipping unrelated tests sometimes helps, commenting lines that could not cause such an error sometimes helps too.
The codebase has enzyme and RTL tests, but all tests that call this code use enzyme.
I could not find anything helpful since all the issues regarding similar issues only apply to RTL and even if applied to not fix this issue.
Issue 1,
Issue 2
Local reproduction is not possible even when running it in docker like Bitbucket pipelines.
Thanks in advance!

React-Native tests failed

i searched on stackoverflow but i didn't find my problem.
I dev an apps only on android, using React-Native-cookies's native module, and now i have to create some unit test. I am using Jest, and i make one.
But now, everytime i want to test it, it is not possible because i didn't configured my xCode project. It doesn't take sense because i haven't changed evything on the ios app. Here is my error :
> jest
PASS __tests__\index.ios.js
FAIL __tests__\index.android.js
● Test suite failed to run
Invariant Violation: react-native-cookies: Add RNCookieMangerIOS.h and RNCookieManagerIOS.m to your Xcode project
at invariant (node_modules/invariant/invariant.js:42:15)
at Object.<anonymous> (node_modules/react-native-cookies/index.js:10:1)
at Object.<anonymous> (App/App/Cookie.js:7:25)
at Object.<anonymous> (App/App/Mattermost.js:11:13)
FAIL App\App\__tests__\Mattermost.test.js
● Test suite failed to run
Invariant Violation: react-native-cookies: Add RNCookieMangerIOS.h and RNCookieManagerIOS.m to your Xcode project
at invariant (node_modules/invariant/invariant.js:42:15)
at Object.<anonymous> (node_modules/react-native-cookies/index.js:10:1)
at Object.<anonymous> (App/App/Cookie.js:7:25)
at Object.<anonymous> (App/App/Mattermost.js:11:13)
Test Suites: 2 failed, 1 passed, 3 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 1.547s, estimated 3s
Ran all test suites.
npm ERR! Test failed. See above for more details.
So i wonder if someone could help me? Thanks
EDIT : forgetted to post the unit test :
import Mattermost from "../Mattermost";
let mattermost = new Mattermost();
test('Rendering Test', () => {
mattermost.setState({
MMAUTHTOKEN : "test debug",
});
expect(mattermost.render.contain(<WebView ref={'webview'} automaticallyAdjustContentInsets={false} style={Style.webview} source={{uri: URLMATTERMOST}} javaScriptEnabled={true} onNavigationStateChange={this.onNavigationStateChange.bind(this)} startInLoadingState={true} scalesPageToFit={true}/>)).to.equal(true);
});

Getting error: Error while waiting for Protractor to sync with the page: {}

My e2e.conf.coffee file is:
exports.config =
baseUrl: 'http://localhost:9001'
specs: [
'e2e/**/*.coffee'
]
framework: 'jasmine'
I have my node project running and listening on port 9001.
My test is:
describe 'Happy Path', ->
it 'should show the login page', ->
console.log browser
expect(browser.getLocationAbsUrl()).toMatch("/view1");
it 'should fail to login', ->
setTimeout ->
console.log "FAIL!"
, 1200
And the error that I get is:
Failures:
1) Happy Path should show the login page
Message:
Error: Error while waiting for Protractor to sync with the page: {}
Stacktrace:
Error: Error while waiting for Protractor to sync with the page: {}
at <anonymous>
at <anonymous>
at <anonymous>
at <anonymous>
at <anonymous>
at <anonymous>
at <anonymous>
at <anonymous>
at <anonymous>
at <anonymous>
at <anonymous>
at <anonymous>
at <anonymous>
==== async task ====
WebDriver.executeScript()
at <anonymous>
at <anonymous>
at <anonymous>
at <anonymous>
at <anonymous>
at <anonymous>
at <anonymous>
at <anonymous>
at <anonymous>
at <anonymous>
at <anonymous>
==== async task ====
Asynchronous test function: it("should show the login page")
at <anonymous>
at <anonymous>
at <anonymous>
at <anonymous>
at <anonymous>
at <anonymous>
at <anonymous>==== async task ====
What am I doing wrong??
The (very) short version: use browser.driver.get instead of browser.get.
The longer version: Protractor is basically a wrapper around Selenium and its Javascript WebDriver code. Protractor adds code to wait for Angular to "settle down" (i.e., finish going through its $digest loops) before proceeding with your test code. However, if your page doesn't have Angular on it, then Protractor will wait "forever" (actually just until it times out) waiting for Angular to settle.
The browser object that Protractor exposes to your test is an instance of Protractor (i.e., if you see old answers on Stack Overflow with var ptor = protractor.getInstance(); ptor.doSomething(), then you can replace ptor with browser in those old answers). Protractor also exposes the wrapped Selenium WebDriver API as browser.driver. So if you call browser.get, you're using Protractor (and it will wait for Angular to settle down), but if you call browser.driver.get, you're using Selenium (which does not know about Angular).
Most of the time, you'll be testing Angular pages, so you'll want to use browser.get to get the benefits of Protractor. But if your login page doesn't use Angular at all, then you should be using browser.driver.get instead of browser.get in the tests that test your login page. Do note that you'll also need to use the Selenium API rather than the Protractor API in the rest of the test: for example, if you have an HTML input element with id="username" somewhere in your page, you'll want to access it with browser.driver.findElement(by.id('username')) instead of element(by.model('username')).
For more examples, see this example from the Protractor test suite (or try this link if the previous one ever goes away). See also the Protractor docs which state:
Protractor will fail when it cannot find the Angular library on a page. If your test needs to interact with a non-angular page, access the webdriver instance directly with browser.driver.
Example code: In your login test above, you would want to do something like:
describe 'Logging in', ->
it 'should show the login page', ->
browser.driver.get "http://my.site/login.html"
// Wait for a specific element to appear before moving on
browser.driver.wait ->
browser.driver.isElementPresent(by.id("username"))
, 1200
expect(browser.driver.getCurrentUrl()).toMatch("/login.html");
it 'should login', ->
// We're still on the login page after running the previous test
browser.driver.findElement(by.id("username")).sendKeys("some_username")
browser.driver.findElement(by.id("password")).sendKeys("some_password")
browser.driver.findElement(by.xpath('//input[#type="submit"]')).click()
(A note of caution: I haven't done much CoffeeScript, and it's entirely possible I made a CoffeeScript syntax error in the code above. You may want to check its syntax before blindly copying and pasting it. I am, however, confident in the logic, because that's copied and pasted almost verbatim from my Javascript code that tests a non-Angular login page.)
If you need to be using browser.get and are getting this error,
the issue is most likely to be the rootElement property in protractor config file.
By default Protractor assumes that the ng-app declaration sits on the BODY-element. However, in our case, it could be declared somewhere else in the DOM. So we have to assign the selector of that element to the rootElement property:
// rootElement: 'body', // default, but does not work in my case
rootElement: '.my-app', // or whatever selector the ng-app element has
Corresponding HTML:
<div ng-app="myApp" class="my-app">
I copied the answer from http://www.tomgreuter.nl/tech/2014/03/timing-errors-with-angular-protractor-testing/
I got this error, too, but in my case my tests were working and this error occured after expanding them.
Turns out that this error may occur, if you try to call getText() in your describe block instead of your testcases. My Set-Up was like following:
describe('Test Edit Functionality', function() {
var testEntry = $$('.list-entry').first(),
testEntryOldName = testEntry.getText();
it('Should keep old name if edit is aborted', [...]);
});
That caused the Error Error while waiting for Protractor to sync with the page: {}.
I fixed it by moving the assigment into a beforeEach-block
describe('Test Delete Functionality', function() {
var testEntry = $$('.list-entry').first(),
testEntryOldName;
beforeEach(function() {
testEntryOldName = testEntry.getText();
});
});
Or, may be better, assign it in the specific testcases you need this value (if you dont need it in all).
Not sure where I picked up the pieces that put this answer at this point, but this is what works for me:
Add class='ng-app' to the element that contains your app.
<div ng-app="myApp" ng-controller="myController" class="ng-app"></div>
Add rootElement to your protractor.conf.
exports.config = {
specs: ['your-spec.js'],
rootElement: ".ng-app"
};
Use browser.driver.get not browser.get.
describe('foobar element', function() {
it('should be "baz" after view is initialized', function() {
browser.driver.get('http://localhost/view');
var inputBox = $('input[name=foobar]');
expect(inputBox.getAttribute('value')).toEqual("baz");
});
});
I got this issue a couple of days back on my CT. My tests were running fine until 3 days back, but then this protractor sync error showed up and just won't go away with any of the solutions/hacks provided here and at https://github.com/angular/protractor/issues/2643.
I checked that this issue only occurred in Firefox headless and worked fine with Chrome headless. Upgrading from Firefox v69 to the latest(v72 currently) fixed the issue. I do not know why the issue started manifesting itself and how it got fixed with the upgrade, but for what it is worth I thought this information might come in handy for someone else.

Resources