More than one test fails due to import after jest is torn down - Supertest Typescript and Express API - express

I am running into an issue where I am running multiple tests using supertest and jest. When there is only one test running then it works just fine but the second one throws the following error:
ReferenceError: You are trying to `import` a file after the Jest environment has been torn down.
I tested this with two very simple tests:
describe("Default API", () => {
describe("Default:", () => {
it("should create a user in the DB", (done) => {
request(app).get("/").expect(200, done);
});
it("should create a user in the DB", (done) => {
request(app).get("/").expect(200, done);
});
});
});
They are the same but the second one throws the error. If I run only the first one there is no issue. This must be a setup issue Does anyone have advice. In my index.ts where I have the main express code I export app as follows:
export default app;
This is at the bottom of the index.ts file.

I had the simular problem and toggle down the issue, in my case I want to use mysql2 to access mariadb. That Module try to autodetect the charset and do to try to lacy loading that encoding.
But I have not found a solution for that for now.

Related

Cypress changes headers to lazyUpdate

I'm running Cypress (10.4.0) with an Angular (10.1.6) project and I'm running into an issue with the headers. At some point during a test the headers are moved into something called lazyUpdate:
Which causes an error with http.js:
Which crashes the application.
My test is fairly simple:
describe('Login with an custom email-address', () => {
it('Visits the login page', () => {
cy.visit('/');
});
it('fills in the login form', () => {
cy.el('inputEmailAddress').type(Cypress.env('EMAIL'));
cy.el('inputPassword').type(Cypress.env('PASSWORD'));
cy.el('buttonLogin').click();
cy.url().should('not.contain', 'login');
});
});
When I use the application myself the headers never change to the lazyUpdate headers.
The issue was that we use some values from local storage to set the headers, but Cypress clears out local storage between tests causing headers to get undefined. Using the cypress-localstorage-commands plugin to store and retrieve headers between tests resolved the issue.

Test execution is different between Github Actions and local

I'm testing my express.js API via importing the root app instance and using it through chai-http. The tests are run via mocha.
As the title say, when I run my tests via Github Actions the results are different than when they are run locally. On Github Actions, I get an automatic 503 error from express on any of the test requests or any type of request, while locally all tests run fine and pass. When the 503 is received the entire test runner hangs as well and doesn't exit until the MongoDB driver times out with an error.
Initially the test timed out so I added --timeout 15000 to bypass it, hopefully temporarily.
This is the general setup and imports done before the tests
import {server} from "../bld/server.js";
import {join} from "path";
import chai from "chai";
import chaiHttp from "chai-http";
import chaiAjv from "chai-json-schema-ajv";
chai.use(chaiHttp);
chai.use(chaiAjv);
const api = !!process.env.TEST_MANUAL
? (process.env.API_ADDRESS ?? "http://localhost") + ":" + (process.env.API_PORT ?? "8000")
: server;
console.log((typeof api == "string")
? `Using manually hosted server: "${api}"`
: "Using imported server instance");
const request = chai.request;
const expect = chai.expect;
And the first test looks like this
describe("verification flow", () => {
const actionUrl = "/" + join("action", "verify", "0");
var response;
describe("phase 0: getting verification code", () => {
it("should return a verification code", async () => {
const res = await request(api).post(actionUrl);
expect(res).to.have.status(201);
expect(res).to.have.json;
expect(res.body).to.have.property("verificationCode");
response = res.body;
});
// ....
});
// ...
});
There are no errors on imports, no errors on attaching the server to chai, and from what I can log no issues with file pathing either. At this point I'm lost to as what could be causing the issue and don't know where to look for the root of the problem.
More specific information below:
Dependencies: https://pastebin.com/tu3n9FkZ
Github Actions: https://pastebin.com/HEk5adWQ
No artifacts (dependencies, builds) have been cached according to logs
Thank you for your time and let me know if you need any more information

Multiple connections with same name are created in e2e test of NestJs with in memory database

I have NestJs application with TypeORM configured with mysql. I want to have e2e(integration) test and for that reason I want to have in memory database in the tests which I configured this way:
{
type: 'sqlite',
database: ':memory:',
synchronize: true,
dropSchema: true,
entities: [`dist/**/*.entity{.ts,.js}`],
}
And the setup of the tests
beforeEach(async () => {
const moduleFixture: TestingModule =
await Test.createTestingModule({imports: [AppModule, UserModule]})
.overrideProvider(TypeOrmConfigService).useClass(MockTypeOrmConfigService)
.compile();
app = await moduleFixture.createNestApplication();
await app.init();
});
. When running the test I got
AlreadyHasActiveConnectionError: Cannot create a new connection named "default", because connection with such name already exist and it now has an active connection session.
at new AlreadyHasActiveConnectionError (/Users/user/workspace/app/src/error/AlreadyHasActiveConnectionError.ts:8:9)
at ConnectionManager.Object.<anonymous>.ConnectionManager.create (/Users/user/workspace/app/src/connection/ConnectionManager.ts:57:23)
at Object.<anonymous> (/Users/user/workspace/app/src/index.ts:228:35)
at step (/Users/user/workspace/app/node_modules/tslib/tslib.js:136:27)
at Object.next (/Users/user/workspace/app/node_modules/tslib/tslib.js:117:57)
at /Users/user/workspace/app/node_modules/tslib/tslib.js:110:75
at new Promise (<anonymous>)
at Object.__awaiter (/Users/user/workspace/app/node_modules/tslib/tslib.js:106:16)
at Object.createConnection (/Users/user/workspace/app/node_modules/typeorm/index.js:186:20)
at rxjs_1.defer (/Users/user/workspace/app/node_modules/#nestjs/typeorm/dist/typeorm-core.module.js:151:29)
(node:19140) UnhandledPromiseRejectionWarning: AlreadyHasActiveConnectionError: Caught error after test environment was torn down
If I move the setup from beforeEach in beforeAll block it's ok, but I'm afraid that when I create several specs the error will come back. How should be handled properly?
EDIT:
The problem was that each test is making a setup of the application and so creates a new connection.The solution was to use "keepConnectionAlive: true," in order all tests to reuse same connection.
keepCOnnectionAlive: true is the way to go
Using keepConnectionAlive: true produced the following error for me.
Jest did not exit one second after the test run has completed.
This usually means that there are asynchronous operations that weren't
stopped in your tests. Consider running Jest with
--detectOpenHandles to troubleshoot this issue.
Adding the below to each e2e test fixed my issue:
afterEach(async () => {
await app.close();
});
Base on 0xCAP's answer, you can do something like this also.
// jest.setup.ts
jest.mock("/path/to/database/config/object", () => {
const { databaseConfig, ...rest } = jest.requireActual("/path/to/database/config/object")
return {
...rest,
databaseConfig: {
...databaseConfig,
keepConnectionAlive: true // replace old config
}
}
})
// jest.config.js
module.exports = {
...other options
setupFilesAfterEnv: ["jest.setup.ts"],
}

XMLHttpRequest is not defined when testing react-native app with jest

i am trying to test a apiwrapper in a react-native based app using jest (integration testing).
When i run it in the iOs simulator everything runs fine however it wont run my jest tests correctly - i always get:
ReferenceError: XMLHttpRequest is not defined
when i try to run tests using my api wrapper, eg.:
it('Login successful with correct data', () => {
let api = Api.getInstance();
return api.login("test", "testpass")
.then(result => expect(result).toEqual('login_successful'));
});
the api class i am trying to test here does use the fetch api (not vanilla xhr). I assume its something related to jest trying to mock something but have not found a way to make it work yet.
Thanks in advance.
In my case, I'm not testing the search code but only importing it somewhere in my code path, so I decided to just mock it at the global level in a setup.js file (loaded using --require at test run). The following works for me:
// needed in react-instantsearch
class XMLHttpRequest {}
global.XMLHttpRequest = XMLHttpRequest;
I had a similar problem with lokka using XMLHttpRequest. I made a mock for lokka, which my api wrapper class depends on. You could try mocking your api wrapper.
This is what my lokka mock looks like for now. I'll add more to it when I start testing error handling.
export default class {
query() {
return new Promise(resolve => {
resolve(200);
});
}
}
You might be able to mock your api wrapper with something similar:
export default class Api {
getInstance() {
\\ However you implemented getInstance
}
login(user, password) {
return new Promise(resolve => {
resolve('login_successful');
});
}
}

Running Knex Migrations Between Mocha Tests

I was using Mocha to test my Nodejs app with a test database. In order to reset the DB before each test I had the following code, which worked perfectly:
process.env.NODE_ENV = 'test';
var knex = require('../db/knex');
describe("Add Item", function() {
beforeEach(function(done) {
knex.migrate.rollback()
.then(function() {
knex.migrate.latest()
.then(function() {
return knex.seed.run()
.then(function() {
done();
});
});
});
});
...
I've since switched from mocha to mocha-casperjs for my integration tests, and now the knex migrations won't run. I'm given this error message with the exact same before each hook:
undefined is not an object (evaluating 'knex.migrate.rollback')
phantomjs://platform/new-item.js:12:17
value#phantomjs://platform/mocha-casperjs.js:114:20
callFnAsync#phantomjs://platform/mocha.js:4314:12
run#phantomjs://platform/mocha.js:4266:18
next#phantomjs://platform/mocha.js:4630:13
phantomjs://platform/mocha.js:4652:9
timeslice#phantomjs://platform/mocha.js:12620:27
I'm pretty sure that migration functionality is not included in webpack build. If you go to http://knexjs.org/ open up debug console and checkout different clients e.g. mysql.migrate you see that there are no functions declared at all.
Actually you can check it out with node too if you explicitly load webpack build instead of node lib.
// load webpack build instead of node build...
let knex = require('knex/build/knex')({client : 'pg'});
console.log(knex.migrate);
// outputs: {}
So... the question is why are you trying to run your tests on PhantomJS browser instead of node.js?