Unlike all of the 'util.promisify is not a function' threads I've seen, I am not explicitly trying to use the 'util.promisify' function.
What I'm trying to do is run database queries during my Cypress tests.
The following method works server-side, but throws a fit client-(browser)-side during Cypress tests:
Database file:
import sql from 'mssql';
export default class Database {
private _databaseConnectionString;
constructor() {
this._databaseConnectionString = 'censored but valid connection string';
};
async query(query: string) {
try {
await sql.connect(this._databaseConnectionString);
const result = await sql.query(query);
return result;
} catch (errorMessage) {
throw new Error(`Error querying database.\n${errorMessage}`);
}
}
}
Test file:
import Database from "../../support/test_data/utilities/database";
const database = new Database();
describe('testing', () => {
it('test', () => {
const aVariable = await database.query(`select * from Users`);
});
});
I isolated what triggers the exception to this line:
await sql.connect(this._databaseConnectionString);
Error:
- An uncaught error was detected outside of a test: TypeError: The following error originated from your test code, not from Cypress.
util.promisify is not a function
When Cypress detects uncaught errors originating from your test code it will automatically fail the current test.
Cypress could not associate this error to any specific test.
We dynamically generated a new test to display this failure.
Please can anyone help? I don't know how to even start troubleshooting this. Is there a better way to run SQL queries during tests? Am I fundamentally doing something wrong?
@JeffBowman is right about the NodeJS requirement. So you can shift the database call to a task, which runs in NodeJs. This is a rough guide:
cypress.config.js
import { defineConfig } from 'cypress'
import Database from "./cypress/support/test_data/utilities/database";
const database = new Database();
export default defineConfig({
e2e: {
setupNodeEvents(on, config) {
on('task', {
dbQuery(query) {
return database.query(query) // promise unwrapped by Cypress
},
})
},
},
})
it('test', () => {
cy.task('dbQuery', 'select * from Users')
.then(results => {
// checking my results here...
...