Configuring e2e tests with NextJS + Tescafe
I have a server-side rendered React app using Next JS and I'm trying to setup end-to-end tests with TestCafe. But when I try to run my tests I get the following error:
1) A JavaScript error occurred on
(...)
Repeat test actions in the browser and check the console for errors.
If you see this error, it means that the tested website caused it. You can fix it or disable
tracking JavaScript errors in TestCafe. To do the latter, enable the "--skip-js-errors" option.
If this error does not occur, please write a new issue at:
"https://github.com/DevExpress/testcafe/issues/new?template=bug-report.md".
JavaScript error details:
Uncaught ReferenceError: window is not defined
No stack trace available
Apparently the test scripts are being executed at server side, so naturally the window object doesn't exist.
Does anyone know how to fix it?
See also questions close to this topic
-
Firebase Cloud function in expo project
So I have a cloud function (this is not in the react native app directory yet):
const admin = require('firebase-admin'); const firebase_tools = require('firebase-tools'); const functions = require('firebase-functions'); admin.initializeApp(); exports.deleteUser = functions .runWith({ timeoutSeconds: 540, memory: '2GB' }) .https.onCall((data, context) => { const userId = context.auth.uid; var promises = []; // DELETE DATA var paths = ['users/' + userId, 'messages/' + userId, 'chat/' + userId]; paths.forEach((path) => { promises.push( recursiveDelete(path).then( () => { return 'success'; } ).catch( (error) => { console.log('Error deleting user data: ', error); }) ); }); // DELETE FILES const bucket = admin.storage().bucket(); var image_paths = ["avatar/" + userId, "avatar2/" + userId, "avatar3/" + userId]; image_paths.forEach((path) => { promises.push( bucket.file(path).delete().then( () => { return 'success'; } ).catch( (error) => { console.log('Error deleting user data: ', error); }) ); }); // DELETE USER promises.push( admin.auth().deleteUser(userId) .then( () => { console.log('Successfully deleted user'); return true; }) .catch((error) => { console.log('Error deleting user:', error); }) ); return Promise.all(promises).then(() => { return true; }).catch(er => { console.error('...', er); }); }); function recursiveDelete(path, context) { return firebase_tools.firestore .delete(path, { project: process.env.GCLOUD_PROJECT, recursive: true, yes: true, token: functions.config().fb.token }) .then(() => { return { path: path } }).catch( (error) => { console.log('error: ', error); return error; }); } // [END recursive_delete_function]
This is used for my swift app. How Can I use this for my react native app built with Expo?
I have installed the following
yarn add @react-native-firebase/functions
I have my firebase.js file set up in the root directory:
import * as firebase from "firebase"; // Your web app's Firebase configuration var firebaseConfig = { apiKey: "test", authDomain: "test", databaseURL: "test", projectId: "test", storageBucket: "test", messagingSenderId: "test", appId: "test" }; // Initialize Firebase firebase.initializeApp(firebaseConfig); export default firebase;
I have a button:
<Text>Delete Account</Text> <View> <Button title="Delete Account" color="#F9578E" accessibilityLabel="Delete Account" /> </View>
Which when clicked signs the user out and runs the above cloud function.
-
Cleaner, better way to pass function callback and state to a child component in React?
Right now I am passing a callback function and the current state to a child component from my Parent component. I just feel like the way I write it is ugly or at least could be prettier. Here is the Parent component where I am passing all that (
parentCallback={[moreReviews, limit]}
in the return):const Reviews: FunctionComponent = () => { const [filter, setFilter] = useState([1, 2, 3, 4, 5]); const [order, setOrder] = useState('date_desc'); const [reviews, setReviews] = useState([]); const [limit, setLimit] = useState(1); let variables = { offset: 0, limit: limit, filter: filter, order: order } const {data: dataReviews, loading: loadingReviews, error: errorReviews} = useQuery(GetReviews, { ssr: false, variables: variables, fetchPolicy: "no-cache" }); useEffect(() => { console.log('action going on deps change'); if (!loadingReviews && !errorReviews && dataReviews) { setReviews(!loadingReviews && !errorReviews && dataReviews ? dataReviews.reviews[0].reviews : []); } }, [dataReviews]); function moreReviews(limit: number) { setLimit(limit); } return reviews.length ? ( <div> <div className={`${styles.netreviews_review_rate_and_stars}`}> <ReviewsSideInfo/> <ReviewsContainer reviews={reviews} parentCallback={[moreReviews, limit]} /> </div> </div> ) : <div/>; }; export default Reviews;
And then in my child component I'm accessing it like so :
<button onClick={() => parentCallback[0](parentCallback[1] + 1)}></button>
That is definitely ugly but its working fine.
Also, and probably more importantly, is a better, more efficient way to do that, from a technical point of view ? Thanks
-
Django load text file into html file using jquery
I want to implement this example code from w3schools.com using Django. The code loads a text file into a html file using the jquery
load()
function. The code looks like this<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("#div1").load("demo_test.txt"); }); }); </script> </head> <body> <div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div> <button>Get External Content</button> </body> </html>
My question is now, how do I store my text file such that the load function has access to it in my Django project?
-
How can I use react-spring useTransition to go from left to right or viceversa
I have a Switch and a Router, and whenever the route changes, it goes from left to right, I would like to know if there's a simple way that the animation can go from right to left based on the change of the route. Thanks in advance.
https://codesandbox.io/s/page-transition-with-react-router-and-react-spring-b07jp
I found this example online, and for instance, I would like to know how can it go from right to left when you click profile.
-
Widget build with webpack and external assets
My goal is to build js library with some widgets. This library will be used on many different websites, domains etc...
It will be imported on page like normal
jquery
library and it will be hosted on domain e.g.libhome.com
like this:<script src="https://libhome.com/static/lib.js"></script>
This library is build using webpack. It contains react inside and a lot of assets (css, images, fonts). So in some components I'm using such syntax:
import 'assets/styles.css';
Now the question. Let's focus on one asset type for now:
css
. When I try to import and uselib.js
inindex.html
hosted onlibhome.com
then the above import works as expected. So when mylibhome.com/index.html
file contains this import:<script src="https://libhome.com/static/lib.js"></script>
Then this library that is build by webpack can import
assets/styles.css
and inject it intohtml
page inhead
section. In my public folder there isassets
folder withstyles.css
inside and this file is available on:https://libhome.com/assets/styles.css
.On the other hand if this library will be imported on different page. For example let's assume that:
https://other.com/index.html
want to import this js library like this:<script src="https://libhome.com/static/lib.js"></script>
It is imported without any problems but
assets/styles.css
are not injected into thishtml
page inhead
section and I don't know why. I even don't know how to debug this using Chrome Developer Tools because there is no error in network traffic. There is no request forassets/styles.css
at all.I just want to build library that can be imported on any webpage and this library should be able to load assets from
https://libhome.com
and not from domain that this library is imported to because there is no assets folder at all on page that imports this library. For example google maps widget can be imported from external domain and all assets are also imported from external domain.Can somebody give me some hints how to configure
webpack
so this:import 'assets/styles.css';
Will be working fine even if script is loaded on totally different domain? I'm using webpack 4 project ejected from Create React App. In configuration there is plugin: MiniCssExtractPlugin which extracts css to file
assets/styles.css
. -
How can make an Automatic tests for Teradata
I am using SQL Teradata. My team and I are looking for a tool to automate testing. I'm not talking about a data quality test tool that I can do with a tool like Talend Data Quality.
I'm looking for a tool for the automation of tests for SQL Teradata.
Does someone have an idea?
thanks in advance,
Best regards, Slim
-
test cafe : removeRequestHook
So I use t.addRequestHooks to add a few requestMock
I have the impression that after the end on my test, the hook are still working.
Is there a way to remove all the requestMock in one line? or should I specify all the t.removeRequestHooks one by one?
-
How to test custom gradle plugin both with JUnit and manually in same sample project
My goal is to have this project setup:
example-gradle-plugin ├── build.gradle └── src ├── main │ ├── java │ │ └── com .... └── test ├── java │ └── example │ └── integrationtest │ │ # GradleRunner.create().withProjectDir(testProjectPath.toFile()).withPluginClasspath() │ └── SimpleProjectRegressionTest.java // └── resources └── simple │ # plugins { id "example-gradle-plugin" } ├── build.gradle │ # // includeBuild ../../../../example-gradle-plugin └── settings.gradle
So the folder src/test/resources/simple is both used from a JUnit test, but as well can be used to run gradle commands from the command line using the composite build approach.
So this should work
cd src/test/resources/simple gradle build
And this unit test should also work:
@Test public void testBuildSample() { final ClassLoader classLoader = ProjectSetupHelper.class.getClassLoader(); final Path sampleSourceRootPath = Paths.get(classLoader.getResource("simple").toURI()); final BuildResult result = GradleRunner.create() .withProjectDir(sampleSourceRootPath.toFile()) .withArguments("build") .withPluginClasspath() .build(); }
However, there is a caveat when running JUnit, the custom-plugin-sources are referred to in 2 different ways at the same time:
GradleRunner.create().withProjectDir(testProjectPath.toFile()).withPluginClasspath()
means to add project custom plugin files to the classpath for running the build during the unit test- In
src/test/resources/simple/settings.gradle
, theincludeBuild ...
command also refers to the custom plugin.
Is there an easier or cleaner way to achieve the above: Having a sample project with composite build that can be used from the commandline to verify local changes to the plugin, and using that sample project also in a unit test of the plugin?
Currently in the unit test I copy the sample folder to a temporary folder without settings.gradle to avoid such complications.
-
Nextjs project not rendering on localhost
Page not showing up on command
npm run dev
ERROR: ready - started server on 0.0.0.0:3000, url: http://localhost:3000 event - compiled successfully event - build page: / wait - compiling... event - compiled successfully<--- Last few GCs --->
[9730:0x4c43fe0] 21576 ms: Mark-sweep (reduce) 2043.9 (2083.5) -> 2043.9 (2083.5) MB, 648.7 / 0.0 ms (average mu = 0.238, current mu = 0.207) allocation failure GC in old space requested
<--- JS stacktrace --->
FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory 1: 0xa747f0 node::Abort() [node] 2: 0x9a1c4d node::FatalError(char const*, char const*) [node] 3: 0xc5d08e v8::Utils::ReportOOMFailure(v8::internal::Isolate*, char const*, bool) [node] 4: 0xc5d407 v8::internal::V8::FatalProcessOutOfMemory(v8::internal::Isolate*, char const*, bool) [node] 5: 0xe26c95 [node] 6: 0xe2783c [node] 7: 0xe351cb v8::internal::Heap::CollectGarbage(v8::internal::AllocationSpace, v8::internal::GarbageCollectionReason, v8::GCCallbackFlags) [node] 8: 0xe379ce v8::internal::Heap::CollectAllAvailableGarbage(v8::internal::GarbageCollectionReason) [node] 9: 0xe38f1b v8::internal::Heap::AllocateRawWithRetryOrFailSlowPath(int, v8::internal::AllocationType, v8::internal::AllocationOrigin, v8::internal::AllocationAlignment) [node] 10: 0xdfcdea v8::internal::Factory::NewFillerObject(int, bool, v8::internal::AllocationType, v8::internal::AllocationOrigin) [node] 11: 0x1153cb8 v8::internal::Runtime_AllocateInOldGeneration(int, unsigned long*, v8::internal::Isolate*) [node] 12: 0x14ea8f9 [node] Aborted (core dumped) npm ERR! code 134 npm ERR! path /home/harsh/Documents/passion_to_choose npm ERR! command failed npm ERR! command sh -c next dev
npm ERR! A complete log of this run can be found in: npm ERR! /home/harsh/.npm/_logs/2021-02-27T14_41_35_238Z-debug.log
LOGFILE:
0 verbose cli [ '/usr/local/bin/node', '/usr/local/bin/npm', 'run', 'dev' ] 1 info using npm@7.5.1 2 info using node@v15.8.0 3 timing config:load:defaults Completed in 1ms 4 timing config:load:file:/usr/local/lib/node_modules/npm/npmrc Completed in 1ms 5 timing config:load:builtin Completed in 1ms 6 timing config:load:cli Completed in 1ms 7 timing config:load:env Completed in 0ms 8 timing config:load:file:/home/harsh/Documents/passion_to_choose/.npmrc Completed in 0ms 9 timing config:load:project Completed in 0ms 10 timing config:load:file:/home/harsh/.npmrc Completed in 1ms 11 timing config:load:user Completed in 1ms 12 timing config:load:file:/usr/local/etc/npmrc Completed in 0ms 13 timing config:load:global Completed in 0ms 14 timing config:load:cafile Completed in 0ms 15 timing config:load:validate Completed in 1ms 16 timing config:load:setUserAgent Completed in 0ms 17 timing config:load:setEnvs Completed in 1ms 18 timing config:load Completed in 6ms 19 verbose npm-session 1d23485429c0f6d1 20 timing npm:load Completed in 10ms 21 timing command:run-script Completed in 22620ms **22 verbose stack Error: command failed 22 verbose stack at ChildProcess. (/usr/local/lib/node_modules/npm/node_modules/@npmcli/promise-spawn/index.js:64:27) 22 verbose stack at ChildProcess.emit (node:events:378:20) 22 verbose stack at maybeClose (node:internal/child_process:1067:16) 22 verbose stack at Process.ChildProcess._handle.onexit (node:internal/child_process:301:5) 23 verbose pkgid passion_to_choose@0.1.0 24 verbose cwd /home/harsh/Documents/passion_to_choose 25 verbose Linux 5.8.0-44-generic 26 verbose argv "/usr/local/bin/node" "/usr/local/bin/npm" "run" "dev" 27 verbose node v15.8.0 28 verbose npm v7.5.1 29 error code 134 30 error path /home/harsh/Documents/passion_to_choose 31 error command failed 32 error command sh -c next dev 33 verbose exit 134
-
POST Request returns 504 Online but works locally
Introduction
My POST request works offline i.e. on localhost, but doesn't work when the website is deployed.
I am using nextjs, node, nodemailer, axios and nginx. I have also used fetch instead of axios and it gave me the same issue.
The situation
I have a handleSubmit function, that takes some inputs from a contact form and sends it to my Gmail account:
axios({ method: "POST", url: "/api/submit", data: body, headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' } }).then((response) => { if (response.data.status === 'success') { alert("Email sent, awesome!"); } else { alert("Oops, something went wrong. Try again") } })
The api/submit.js is as follows:
import nodemailer from "nodemailer" var transport = { service: 'gmail', host: "smtp.gmail.com", port: 587, secure: false, auth: { user: process.env.USER, pass: process.env.PASS } } var transporter = nodemailer.createTransport(transport); transporter.verify((error, success) => { if (error) { console.log("There was an error:" + error); } else { console.log("Server is ready to take messages") } }) export default async (req, res) => { switch (req.method) { case "POST": var name = req.body.name; var content = name " text " var mail = { from: name, to: "myemail@gmail.com", text: content } transporter.sendMail(mail, (err, data) => { if (!err) { res.json({ status: "success" }) res.end(); } }) break case "GET": res.status(200).json({name:"John Doe"}) break default: res.status(405).end() break } }
The code works locally when I run npm run dev, or npm start it posts to http://localhost:3000/api/submit and I receive the email within seconds.
However, when I deploy the website on DigitalOcean and hit the submit button nothing happens for 60 seconds then I get a status code of 504 on my POST request. If I send a GET request to api/submit, it works and I see the JSON for that request, so it's an issue with the POST request specifically.
My Nginx logs it as the following:
2021/02/27 13:59:35 [error] 95396#95396: *3368 upstream timed out (110: Connection timed out) while reading response header from upstream, client: my.ip, server: website.com, request: "POST /api/submit HTTP/1.1", upstream: "http://127.0.0.1:3000/api/submit", host: "website.com", referrer: "https://website.com/contact"
I've been trying to debug it for days now, but I just can't figure it out. Anyone have any ideas?
-
Next.js Authentication with JWT
I am moving a project from React to Next.js and was wondering if the same authentication process is okay. Basically, the user enters their username and password and this is checked against database credentials via an API (Node.js/Express). So, I am not using Next.js internal api functionality, but a totally decoupled API from my Next.js project.
If the login credentials are correct, a JWT token is sent back to the client. I wanted to store that in local storage and then redirect the user. Any future http requests will send the token in the header and check it is valid via the API. Is this okay to do? I ask because I see a lot of Next.js auth using cookies or sessions and don't know if that is the 'standard' approach which I should rather adopt.
-
Trying to run testcafe with jenkins manually but getting error
hello I followed everything in this article https://devexpress.github.io/testcafe/documentation/guides/continuous-integration/jenkins.html
When I am running it shows this error:
ERROR ReferenceError: globalThis is not defined at Object. (E:\jenkins\builds\workspace\Automation\node_modules\queue-microtask\index.js:5:25) at Module._compile (internal/modules/cjs/loader.js:707:30) at Module._compile (E:\jenkins\builds\workspace\Automation\node_modules\source-map-support\source-map-support.js:547:25) at Object.Module._extensions..js (internal/modules/cjs/loader.js:718:10) at Module.load (internal/modules/cjs/loader.js:605:32) at tryModuleLoad (internal/modules/cjs/loader.js:544:12) at Function.Module._load (internal/modules/cjs/loader.js:536:3) at Module.require (internal/modules/cjs/loader.js:643:17) at require (internal/modules/cjs/helpers.js:22:18) at Object. (E:\jenkins\builds\workspace\Automation\node_modules\run-parallel\index.js:4:24) at Module._compile (internal/modules/cjs/loader.js:707:30) at Module._compile (E:\jenkins\builds\workspace\Automation\node_modules\source-map-support\source-map-support.js:547:25) at Object.Module._extensions..js (internal/modules/cjs/loader.js:718:10) at Module.load (internal/modules/cjs/loader.js:605:32) at tryModuleLoad (internal/modules/cjs/loader.js:544:12) at Function.Module._load (internal/modules/cjs/loader.js:536:3) at Module.require (internal/modules/cjs/loader.js:643:17) at require (internal/modules/cjs/helpers.js:22:18) at Object.
What am i doing wrong ? how can i resolve this GlobalThis error?
-
Integration of qtest test management tool and testcafe automation tool
I have test cases automated in testcafe. How do I integrate this testcafe with qtest tool to manage the testing?