Setting up Cypress.config file for SQL database testing with Cypress

Currently, I am looking to experiment with SQL databases. I have SqlWorkbench installed and have mysql added in my package file.

However, I encountered an issue while attempting to run Cypress as SyntaxError: Unexpected token 'export'

The problem seems to be related to the code in cypress.config.ts (My local files contain data within the defineConfig)

import { defineConfig } from "cypress";
import mysql from 'mysql';

function queryTestDB(query,config) {
  const connection = mysql.createConnection(config.env.db)

  connection.connect()
  return new Promise((resolve, reject) => {
    connection.query(query, (error, results) => {
      if (error) {
        return reject(error)
      }
      connection.end()
      return resolve(results)
    })
  })
}

export default defineConfig({
  projectId: '...',
  env: {
    db: {
      host: '...',
      user: '...',
      password: '...',
      database: '...',
    }
  },
  e2e: {
    baseUrl: 'http://localhost...',
    setupNodeEvents(on, config) {
      on('task', {
        queryDB(query) {
          return queryTestDB(query,config)
        }
      })
    }
  },
});

Answer №1

import { defineConfig } from 'cypress';
const mysql = require('mysql2'); 

function querytestDB(query: string, config) {
  const connection = mysql.createConnection(config.env.db);

  connection.connect()

  return new Promise((resolve, reject) => {
    connection.query(query, (error, results) => {
      if (error) {
        return reject(error)
      }

      connection.end()
      return resolve(results)
    });
  });
}

export default defineConfig({
  env : {
    db: {
      host: "127.0.0.1",
      user: "...",
      password: "...",
      database: "..."
    }
  },
  e2e: {
    setupNodeEvents(on, config) {
      on('task', {
        queryDB: query=> {
          return querytestDB(query, config)},
      });
    },
    chromeWebSecurity: false,
  },
});

This is located within the cypress.config.ts file :)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the reason for a type narrowing check on a class property failing when it is assigned to an aliased variable?

Is there a way to restrict the type of property of a class in an aliased conditional expression? Short: I am trying to perform a type narrowing check within a class method, like this._end === null && this._head === null, but I need to assign the r ...

Arranging Angular Array-like Objects

I am in possession of an item: { "200737212": { "style": { "make": { "id": 200001510, "name": "Jeep", "niceName": "jeep" }, "model": { "id": "Jeep_Cherokee", "name": "Cherokee", "nice ...

Troubleshooting CORS errors in axios requests within a Next.js application

Encountering an issue while attempting to make an axios call to my API on a different localhost. How can this be resolved? The tech stack being used includes Next.js, TypeScript, and Axios. Below is the function which - although written poorly for testing ...

Tips for converting a date string to a date object and then back to a string in the same format

I seem to be encountering an issue with dates (shocker!), and I could really use some assistance. Allow me to outline the steps I have been taking. Side note: The "datepipe" mentioned here is actually the DatePipe library from Angular. var date = new Dat ...

NodeJS and TypeScript are throwing an error with code TS2339, stating that the property 'timeOrigin' is not found on the type 'Performance'

I am currently working on a NodeJS/TypeScript application that utilizes Selenium WebDriver. Here is an excerpt from the code: import { WebDriver } from "selenium-webdriver"; export class MyClass { public async getTimeOrigin(driver: WebDriver ...

Preventing going back to a previous step or disabling a step within the CDK Stepper functionality

In my Angular application, there is a CdkStepper with 4 steps that functions as expected. Each step must be completed in order, but users can always go back to the previous step if needed. For more information on CdkStepper: https://material.angular.io/cd ...

Exception occurs when arrow function is replaced with an anonymous function

Currently, I am experimenting with the Angular Heroes Tutorial using Typescript. The code snippet below is functioning correctly while testing out the services: getHeroes() { this.heroService.getHeroes().then(heroes => this.heroes = heroes); } H ...

The beforePopState event in next/router is not triggering as expected

Noticing an issue where the beforePopState event is not triggering when I use the back button. This code snippet is part of a hook defined in _app.js according to the documentation. The current version being used is 12.1.5 If anyone has insights on what ...

Creating and handling Observable of Observables in RxJS: Best practices

Within my Angular application, there are multiple services that have dependencies on each other. To manage this, I have created a dependency map as shown in the example below: let accountInitialization$: Observable<void>; let productInitialization$: ...

Having an issue with my code in angular 12 where I am unable to successfully call an API to retrieve a token, and then pass that token to another API for further processing

Here is the code snippet containing two methods: getToken and validateuser. I am fetching the token from getToken and passing it as a parameter to validateuser. However, before retrieving the token, my second API call is being executed. ...

Utilize TypeScript to import a JSON file

I am trying to incorporate a JSON file using TypeScript, which contains data about different regions in Italy along with their respective capitals. Here is a snippet of the data: { "italia": [ { "regione": "Abruzzo", "capoluoghi": [ ...

There is an issue with the Next.js middleware: [Error: The edge runtime is not compatible with the Node.js 'crypto' module]

Struggling with a problem in next.js and typescript for the past 4 days. If anyone can provide some insight or help with a solution, it would be greatly appreciated. Thank you! -- This is my middleware.ts import jwt from "jsonwebtoken"; import { ...

How Angular can fetch data from a JSON file stored in an S3

I am attempting to retrieve data from a JSON file stored in an S3 bucket with public access. My goal is to parse this data and display it in an HTML table. http.get<Post>('https://jsonfile/file.json').subscribe (res => { cons ...

Understanding the data types of functions in TypeScript can be quite important for

What type of information is required after the colon : in this specific function? public saveHistory(log: String): "HERE!" { return async (req: Request, res: Response, next: NextFunction): Promise<Response | void> => { try { ...

Unexpected results observed in enumerators within typescript

Could someone clarify the results that I am seeing from the code below? enum days { sun = 1, mon = 0, tues }; console.log(days[1]); // outputs tues // should output -- mon console.log(days[0]); // outputs mon // should output -- sun Furthermore, how ...

I lost my hovering tooltip due to truncating the string, how can I bring it back in Angular?

When using an angular ngx-datatable-column, I added a hovering tooltip on mouseover. However, I noticed that the strings were too long and needed to be truncated accordingly: <span>{{ (value.length>15)? (value | slice:0:15)+'..':(value) ...

Resolving the Error: "Type 'Customer | undefined' is not compatible with type 'Customer'" in Angular

I encountered an issue with the following code: ... export class ListCustomersComponent implements OnInit { customers: Array<Customer> = []; showCustomer?: Customer; isSelected: boolean = false; deletedCustomer?: Customer; returnedMessa ...

Error displaying messages from the console.log function within a TypeScript script

My node.js application runs smoothly with "npm run dev" and includes some typescript scripts/files. Nodemon is used to execute my code: This is an excerpt from my package.json file: { "scripts": { "start": "ts-node ./src/ind ...

Observable - initiating conditional emission

How can I make sure that values are emitted conditionally from an observable? Specifically, in my scenario, subscribers of the .asObservable() function should only receive a value after the CurrentUser has been initialized. export class CurrentUser { ...

Is it normal that aws-eventbridge-lambda does not generate a Lambda function?

I've been experimenting with the AWS CDK (Typescript) to enhance my knowledge. I'm interested in setting up a lambda function to run daily at a specific time or at intervals of N minutes. Since I anticipate having multiple functions, it would be ...