Jest Node.js Not able to call beforeAll and afterAll properly using separate file - javascript

I have defined beforAll and afterAll in a separate file bootstrap.js but I am not able to do integration testing. I am using serverless stack. I took help from github but that example was written in mocha so I tried to transform it to jest.
bootstrap.js
beforeAll(async () => {
console.log('[Tests Bootstrap] Start');
await startSlsOffline((err) => {
if (err) {
console.log(err);
}
console.log('[Tests Bootstrap] Done');
});
}, 30000);
afterAll(async () => {
console.log('[Tests Teardown] Start');
await stopSlsOffline();
console.log('[Tests Teardown] Done');
});
handler.test.js
describe('get Endpoints', () => {
const server = request(`http://localhost:3005`);
test('should run get example', async () => {
const res = await server.get('/example');
console.log('res', res.body);
});
});
My jest configuration is
module.exports = {
verbose: true,
bail: true,
coverageDirectory: 'output/coverage/jest',
setupFilesAfterEnv: [ './bootstrap.js' ]
};
The output I get is
> jest --config test/jest.config.js
FAIL test/handler.test.js
get Endpoints
✕ should run get example (38ms)
● get Endpoints › should run get example
connect ECONNREFUSED 127.0.0.1:3005
console.log test/bootstrap.js:6
[Tests Bootstrap] Start
console.log test/bootstrap.js:30
Serverless: Offline started with PID : 5587 and PORT: 3005
console.log test/bootstrap.js:18
[Tests Teardown] Start
console.log test/bootstrap.js:47
Serverless Offline stopped
console.log test/bootstrap.js:22
[Tests Teardown] Done
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 2.825s
Ran all test suites.
npm ERR! Test failed. See above for more details.

The global setup doesn't work the way you are expecting it to work. If you see the logs, your beforeAll logs are coming after your test executes. You should use different way to setup and teadown. Jest has concept of globalSetup and globalTeardown and I guess that fits better in your case. As part of this you can start and stop your server. The config will look like this
Read more here - https://jestjs.io/docs/en/configuration#globalsetup-string
module.exports = {
verbose: true,
bail: true,
coverageDirectory: 'output/coverage/jest',
globalSetup: "./bootstrap.js",
globalTeardown: "./bootstrap.js"
};
And your bootstrap will looks like this
const { spawn} = require('child_process');
let slsOfflineProcess;
module.exports = async () => {
console.log('[Tests Bootstrap] Start');
await startSlsOffline((err) => {
if (err) {
console.log(err);
}
console.log('[Tests Bootstrap] Done');
});
}
const startSlsOffline = (done) => {
if (slsOfflineProcess) {
slsOfflineProcess.kill('SIGINT');
console.log('Serverless Offline stopped');
done();
}
slsOfflineProcess = spawn('sls', [ 'offline', 'start', '--port', 3005 ]);
console.log(`Serverless: Offline started with PID : ${slsOfflineProcess.pid} and PORT: 3005`);
slsOfflineProcess.stdout.on('data', (data) => {
if (data.includes('Offline listening on')) {
console.log(data.toString().trim());
done();
}
});
slsOfflineProcess.stderr.on('data', (errData) => {
console.log(`Error starting Serverless Offline:\n${errData}`);
done(errData);
});
};

I solved my issue using this config with help of 1st answer using globalSetup and globalTeardown.
Read more here - https://jestjs.io/docs/en/configuration#globalsetup-string
bootstrap.js
const { spawn } = require('child_process');
let slsOfflineProcess;
module.exports = async () => {
console.log('[Tests Bootstrap] Start');
await startSlsOffline().catch((e) => {
console.error(e);
return;
});
global.__SERVERD__ = slsOfflineProcess;
};
function startSlsOffline() {
slsOfflineProcess = slsOfflineProcess = spawn('sls', [ 'offline', 'start', '--port', 3005 ]);
return finishLoading();
}
const finishLoading = () =>
new Promise((resolve, reject) => {
slsOfflineProcess.stdout.on('data', (data) => {
if (data.includes('Serverless: Offline [HTTP] listening on')) {
console.log(data.toString().trim());
console.log(`Serverless: Offline started with PID : ${slsOfflineProcess.pid}`);
resolve('ok');
}
if (data.includes('address already in use')) {
reject(data.toString().trim());
}
});
slsOfflineProcess.stderr.on('data', (errData) => {
console.log(`Error starting Serverless Offline:\n${errData}`);
reject(errData);
});
});
teardown.js
module.exports = async function() {
let slsOfflineProcess = global.__SERVERD__;
slsOfflineProcess.stdin.write('q\n');
slsOfflineProcess.stdin.pause();
await slsOfflineProcess.kill('SIGINT');
console.log('Serverless Offline stopped');
};
Find a sample on this link here: https://github.com/bilalsha/sls-test-jest
P.S globalTeardown do not works if test fails. I will post solution once I have it.

Related

Manually resolve promise for getPromiseFinishAllItems

I'm using a combination of protractor, selenium, jasmine and report portal for automated testing. The tests all run fine but when it comes to the last test it always hangs and it eventually fails, looking into it, it seems to come down to what is used in the afterAll function in my protractor.conf.js file.
jasmineEnv.afterAll(async (done) => {
await agent.getPromiseFinishAllItems(agent.tempLaunchId);
done();
});
Now the function it calls comes from the node modules reportportal-agent.js :
getPromiseFinishAllItems(launchTempId){
return this.client.getPromiseFinishAllItems(launchTempId)
}
I've noticed that written above this function is the comment
/*
* This method is used for frameworks as Jasmine and other. There is problems when
* it doesn't wait for promise resolve and stop the process. So it better to call
* this method at the spec's function as #afterAll() and manually resolve this promise.
*
* #return a promise
*/
I'm wondering is there a solution for how to properly resolve this promise? I have tried looking online but not found anything of any significance
EDIT -
protractor.conf.js
const ReportportalAgent = require('agent-js-jasmine');
const { SpecReporter } = require('jasmine-spec-reporter');
const suiteSettings = require('./suiteSettings');
const settings = require('./settings');
const logger = require('./tests/helpers/logger');
// This is a temporary solution because we have issues if instances=nodes. For now balance between nodes and instances that instances < 3
const nodeReduceCount = 5;
let isBrowserOpen = false;
exports.config = {
framework: 'jasmine',
seleniumAddress: settings.seleniumHubHost,
capabilities: {
'shardTestFiles': true,
'maxInstances': Math.max(settings.countOfStreams - nodeReduceCount, 1),
'browserName': settings.browser,
'loggingPrefs': {
performance: 'INFO',
},
'moz:firefoxOptions': getFirefoxOptions(),
'goog:chromeOptions': getChromeOptions(),
},
suites: [
suiteSettings.suite,
],
jasmineNodeOpts: {
defaultTimeoutInterval: settings.jasmineTimeout,
isVerbose: false,
includeStackTrace: true,
realtimeFailure: false,
},
onPrepare: async () => {
const jasmineEnv = jasmine.getEnv();
const capabilities = await browser.getCapabilities();
const config = await browser.getProcessedConfig();
global.consoleReporter = [];
console.log(capabilities);
if (!settings.useReportPortal) {
registerReporter(jasmineEnv);
} else {
registerConsoleReporter(jasmineEnv);
}
jasmineEnv.beforeEach(async () => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = settings.jasmineTimeout;
const criticalCheck = String(config.specs);
if (criticalCheck.includes('critical')) {
process.env.RUN_WITH_SERVICE_WORKER = 'true';
} else {
process.env.RUN_WITH_SERVICE_WORKER = '';
}
if (isBrowserOpen) {
browser.restart();
}
await browser.driver.manage().window().setSize(settings.viewPort.width, settings.viewPort.height);
isBrowserOpen = true;
await logger.logMessage(`Opening Link ${settings.newPlanUrl()}`);
await browser.waitForAngularEnabled(false);
await browser.get(settings.newPlanUrl());
});
},
};
function registerReporter(jasmineEnv) {
jasmineEnv.addReporter(new SpecReporter({
spec: {
displayStacktrace: true,
},
}));
const config = {
id: browser.params.id,
...settings.reportPortal,
};
const agent = new ReportportalAgent(config);
const reporter = agent.getJasmineReporter();
jasmineEnv.afterAll(async (done) => {
await agent.getPromiseFinishAllItems(agent.tempLaunchId);
done();
});
global.reporter = reporter;
jasmineEnv.addReporter(reporter);
return agent;
}
function registerConsoleReporter(jasmineEnv) {
jasmineEnv.afterEach(async () => {
await browser.takeScreenshot().then((png) => {
const testSuite = settings.currentSuite;
const date = new Date();
const currentDay = `(Time-${date.getHours()}-${date.getMinutes()}-${date.getSeconds()})`;
logger.writeScreenShot(png, `screenshots/${currentDay}_${testSuite}.png`);
});
});
jasmineEnv.afterAll(async () => {
await console.log('\n---------------------------------');
await console.log('Test Results');
await global.consoleReporter.forEach((testResult) => {
console.log(testResult);
});
await console.log('---------------------------------');
});
}
function getFirefoxOptions() {
const options = {};
if (settings.headless) {
options.args = ['--headless'];
}
return options;
}
function getChromeOptions() {
const options = {
args: [
'--disable-gpu',
'--no-sandbox',
'--disable-extensions',
'--disable-dev-shm-usage',
'--disable-infobars',
],
};
if (settings.headless) {
options.args.push('--headless');
options.perfLoggingPrefs = {
enableNetwork: true,
};
}
return options;
}
Edit:
So the error I had before was due to adding:
agent.getExitPromise.
But I've noticed after removing that and running my test suite again to see if jenkins would log anything useful when it comes to the test that gets interrupted, it says:
13:43:26 Cancelling nested steps due to timeout
13:43:26 ...Sending interrupt signal to process
13:43:31 npm ERR! path /app
13:43:31 npm ERR! command failed
13:43:31 npm ERR! signal SIGTERM
13:43:31 npm ERR! command sh -c node generateTests.js && node start.js
does anyone have any idea what the cause of this could be?
So after comments with Sergey which helped massively. I realised I was looking in the wrong area and tried to think more of what is happening. Looking at the test runs I noticed that the last test was cut off so I figured I must be closing the connection somewhere before the last test has a chance to finish.
What I've done, which seems to work is do:
jasmineEnv.afterAll(async (done) => {
await agent.getPromiseFinishAllItems(agent.tempLaunchId);
await agent.getExitPromise();
done();
});
Getting the exit promise appears to have solved the issue
Okay so I finally found out what the issue was, we had files that were in the incorrect directory. That was it, once these were moved to the correct place, the issue stopped happening and the last test no longer gets hung up. So for anyone else that comes across this issue, this is something to check

Unable to use promise returned by Jest beforeAll

I am trying to write unit tests for my mongodb queries using mongodb-memory-server, mongodb and Jest. I am trying to setup the db from beforeAll and hoping to use the promises returned into my test.
Here is my code which I have developed using the Jest documentation provided in their setup and teardown section:
dbOperations.js
const { MongoMemoryServer } = require('mongodb-memory-server')
const MongoClient = require('mongodb').MongoClient
const testDocument = {
"name" : "test"
}
let client = null
let mongoServer = null
module.exports.initdb = async () => {
mongoServer = new MongoMemoryServer()
const mongoUri = await mongoServer.getUri()
console.log("init db -----------------")
try {
client = await MongoClient.connect(mongoUri, {
useUnifiedTopology: true,
})
const test_db = await client.db(await mongoServer.getDbName()) //generates random DB name.
const test_collection = await test_db.collection("test")
console.log("in function------", await test_db.stats()) // i can see these in output
await test_collection.insertOne(testDocument) // load test data
return {
test_db,
test_collection
}
}
catch(e) {
console.log("Setup Error", e)
}
}
module.exports.teardown = () => {
if (client) {
console.log("closing mongo client")
client.close()
}
if (mongoServer) {
console.log("closing mongo server")
mongoServer.stop()
}
}
And my test.js
const {initdb, teardown} = require('../testUtils/dbOperations')
describe('MongoDB Test Suite', () => {
beforeAll ( () => {
return initdb()
})
afterAll ( () => {
return teardown()
})
test('test connection and document setup ', async () => {
let docCount = await test_collection.countDocuments({})
expect(test_db).toBeDefined()
expect(docCount).toBe(1);
})
})
And my console output :
MongoDB Test Suite
✕ test connection and document setup (3 ms)
● MongoDB Test Suite › test connection and document setup
ReferenceError: test_collection is not defined
15 |
16 | test('test connection and document setup ', async () => {
> 17 | let docCount = await test_collection.countDocuments({})
| ^
18 | expect(test_db).toBeDefined()
19 | expect(docCount).toBe(1);
20 | })
at Object.test (tests/unit-tests/test.js:17:24)
console.log
init db -----------------
at Object.<anonymous>.module.exports.initdb (tests/testUtils/dbOperations.js:14:11)
console.log
in function------ { db: '5129a396-09f4-43ad-8ceb-b843932a3956',
collections: 0,
views: 0,
objects: 0,
avgObjSize: 0,
dataSize: 0,
storageSize: 0,
numExtents: 0,
indexes: 0,
indexSize: 0,
fileSize: 0,
ok: 1 }
at Object.<anonymous>.module.exports.initdb (tests/testUtils/dbOperations.js:21:15)
console.log
Setup Error ReferenceError: test_db is not defined
at Object.<anonymous>.module.exports.initdb (/Users/souparno/Code/aws-lambdas/tests/testUtils/dbOperations.js:24:9)
at process._tickCallback (internal/process/next_tick.js:68:7)
at Object.<anonymous>.module.exports.initdb (tests/testUtils/dbOperations.js:29:15)
console.log
closing mongo client
at teardown (tests/testUtils/dbOperations.js:35:15)
console.log
closing mongo server
at teardown (tests/testUtils/dbOperations.js:39:15)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 0.971 s, estimated 1 s
Everything works normally if I put all my code in a single module. Somehow, when splitting setup functions in a new module, I am unable to utilize the Promise returned by initdb called inside my beforeAll block.
You need to assign the return value of initdb to something:
describe('MongoDB Test Suite', () => {
let test_collection
beforeAll ( async () => {
const result = await initdb()
test_collection = result.test_collection
})
...

Typeorm Connection "default" was not found when connection is created in jest globalSetup

I'm having a similar problem as in #5164 and this question. Consider the following working test code:
// AccountResolver.test.ts
describe('Account entity', () => {
it('add account', async () => {
await createConnections()
const defaultConnection = getConnection('default')
const actual = await callGraphql(
`mutation {
addAccount(options: {
accountIdentifier: "7csdcd8-8a5f-49c3-ab9a-0198d42dd253"
name: "Jake, Bob (Braine-l’Alleud) JAM"
userName: "Bob.Marley#contoso.com"
}) {
accountIdentifier
name
userName
}
}`
)
expect(actual.data).toMatchObject({
data: {
addAccount: {
accountIdentifier: '7csdcd8-8a5f-49c3-ab9a-0198d42dd253',
name: 'Jake, Bob (Braine-l’Alleud) JAM',
userName: 'Bob.Marley#contoso.com',
},
},
})
await defaultConnection.query(`DELETE FROM Account`)
await defaultConnection.close()
})
})
The code to create a connection and close it should be executed before all tests and after all tests are done, that's why we've added it to globalSetup.ts and globalTeardown.ts:
// globalSetup.ts
require('ts-node/register')
import { createConnections } from 'typeorm'
module.exports = async () => {
// console.log('jest setup')
await createConnections()
}
// globalTeardown.ts
require('ts-node/register')
import { getConnection } from 'typeorm'
module.exports = async () => {
const defaultConnection = getConnection('default')
await defaultConnection.close()
}
// AccountResolver.test.ts
describe('Account entity', () => {
it('add account', async () => {
const defaultConnection = getConnection('default')
await defaultConnection.query(`DELETE FROM Account`)
const actual = await callGraphql(
`mutation {
addAccount(options: {
accountIdentifier: "7csdcd8-8a5f-49c3-ab9a-0198d42dd253"
name: "Jake, Bob (Braine-l’Alleud) JAM"
userName: "Bob.Marley#contoso.com"
}) {
accountIdentifier
name
userName
}
}`
)
expect(actual.data).toMatchObject({
data: {
addAccount: {
accountIdentifier: '7csdcd8-8a5f-49c3-ab9a-0198d42dd253',
name: 'Jake, Bob (Braine-l’Alleud) JAM',
userName: 'Bob.Marley#contoso.com',
},
},
})
})
})
Omitting the line require('ts-node/register') from both files throws this error:
T:\Test\src\it-portal\entity\Account.ts:1
import {
^^^^^^
SyntaxError: Cannot use import statement outside a module
Keeping the require line in throws:
FAIL src/resolvers/AccountResolver.test.ts × add account (31 ms) ●
Account entity › add account ConnectionNotFoundError: Connection
"default" was not found.Account entity
Version
"jest": "^26.0.1",
"ts-jest": "^26.1.0",
"ts-node-dev": "^1.0.0-pre.44",
"typescript": "^3.9.5"
Config
// jest.config.js
module.exports = {
preset: 'ts-jest',
globalSetup: './src/test-utils/config/globalSetup.ts',
globalTeardown: './src/test-utils/config/globalTeardown.ts',
setupFiles: ['./src/test-utils/config/setupFiles.ts'],
moduleDirectories: ['node_modules', 'src'],
globals: {
'ts-jest': {
tsConfig: 'tsconfig.json',
diagnostics: {
warnOnly: true,
},
},
},
coverageThreshold: {
global: {
branches: 80,
functions: 80,
lines: 80,
statements: 80,
},
},
coverageReporters: ['json', 'lcov', 'text', 'clover'],
}
Thank you for pointing out my mistakes. As I'm new I tried googling but couldn't really find an answer if this is me not understanding the tool or a bug in the too. Found a similar issue here with a PR.
It seems like the tests are running in a fully isolated environment where they can't access the connection set up within globalSetup.
Workaround
The only workaround I have found thus far is to add the following code to every test file:
beforeAll(async () => {
await createConnections()
})
afterAll(async () => {
const defaultConnection = getConnection('default')
await defaultConnection.close()
})
require('ts-node/register') shouldn't present in .ts files. They are already processed by TypeScript compiler.
This is not what globalSetup and globalTeardown are for. They run in Jest parent process and are evaluated once, while each test suite runs in child processes.
This can be achieved by providing a common setup in setupFilesAfterEnv option:
// jest.setup.ts
...
beforeAll(async () => {
await createConnections()
})
afterAll(async () => {
const defaultConnection = getConnection('default')
await defaultConnection.close()
})
Since Jest tests run in parallel, this will result in multiple database connections. If this is not desirable because of connection limit, Jest runInBand option needs to be used.
A setup for all tests not desirable because not all test suites need database connection, while they will unconditionally take time and occupy database connection pool. In this case jest.setup.ts can be imported directly in tests that use a database instead of setupFilesAfterEnv, no need to specify beforeAll and afterAll in each suite.

Start and stop server with supertest

I have the following server class :
import express, { Request, Response } from 'express';
export default class Server {
server: any;
exp: any;
constructor() {
this.exp = express();
this.exp.get('/', (_req: Request, res: Response) => {
res.json('works');
});
}
start(): void {
this.server = this.exp.listen(3000);
}
stop(): void {
this.server.close();
}
}
I'm using supertest for end-to-end testing. I wish to start my application beforeAll tests and stop it when the tests are done.
It's easy to do that using beforAll and afterAll where I can just once instanciate the Server class and call the start and close methods.
But as I have 10+ controllers to test, I want to avoid to start and stop the server during each test file.
I found on the documentation the setupFiles and setupFilesAfterEnv but I can't stop the server since the instance is not "shared" in the two files.
This is an example of 1 test file :
import supertest from 'supertest';
describe('Album Test', () => {
let app: App;
beforeAll(async (done) => {
app = new App();
await app.setUp(); // database connection (not mentionned in the preivous example)
done();
});
afterAll(async (done) => {
await app.close();
app.server.stop();
done();
});
const api = supertest('http://localhost:3000');
it('Hello API Request', async () => {
const result = await api.get('/v1/user');
expect(result.status).toEqual(200);
...
});
});
This works totally fine but I'm duplicating this beforeAll and afterAll methods in every test file. Is there a way to declare it only once ?
Thanks
Try this it works
const supertest = require('supertest')
const app = require('../../app')
describe('int::app', function(){
let request = null
let server = null
before(function(done){
server = app.listen(done)
request = supertest.agent(server)
})
after(function(done){
server.close(done)
})
it('should get /api/v1/laps/85299', function(){
return request.get('/api/v1/laps/85299')
.expect(200, { data: {} })
})
})
You could use setupFiles to set up test fixtures globally. You can assign variables that you want to use in multiple test files to Node.js global object.
E.g.
app.ts:
import express, { Request, Response } from 'express';
export default class Server {
server: any;
exp: any;
constructor() {
this.exp = express();
this.exp.get('/', (_req: Request, res: Response) => {
res.json('works');
});
}
start(): void {
this.server = this.exp.listen(3000);
}
stop(): void {
this.server.close();
}
}
app.setup.js:
const App = require('./app').default;
beforeAll(() => {
global.app = new App();
global.app.exp.set('test setup', 1);
console.log('app setup');
});
afterAll(() => {
console.log('app stop');
});
jest.config.js:
module.exports = {
preset: 'ts-jest/presets/js-with-ts',
testEnvironment: 'node',
setupFilesAfterEnv: [
'./jest.setup.js',
'/Users/ldu020/workspace/github.com/mrdulin/react-apollo-graphql-starter-kit/stackoverflow/61659975/app.setup.js',
],
testMatch: ['**/?(*.)+(spec|test).[jt]s?(x)'],
verbose: true,
};
a.controller.test.js:
describe('controller a', () => {
it('should pass', () => {
console.log('test setup:', global.app.exp.get('test setup'));
expect(1 + 1).toBe(2);
});
});
b.controller.test.js:
describe('controller b', () => {
it('should pass', () => {
console.log('test setup:', global.app.exp.get('test setup'));
expect(1 + 1).toBe(2);
});
});
unit test results:
PASS stackoverflow/61659975/a.controller.test.js
controller a
✓ should pass (5ms)
console.log
app setup
at Object.<anonymous> (stackoverflow/61659975/app.setup.js:6:11)
console.log
app setup
at Object.<anonymous> (stackoverflow/61659975/app.setup.js:6:11)
console.log
test setup: 1
at Object.<anonymous> (stackoverflow/61659975/b.controller.test.js:3:13)
console.log
test setup: 1
at Object.<anonymous> (stackoverflow/61659975/a.controller.test.js:3:13)
console.log
app stop
at Object.<anonymous> (stackoverflow/61659975/app.setup.js:10:11)
console.log
app stop
at Object.<anonymous> (stackoverflow/61659975/app.setup.js:10:11)
PASS stackoverflow/61659975/b.controller.test.js
controller b
✓ should pass (3ms)
Test Suites: 2 passed, 2 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 6.749s, estimated 12s

Seed db with sequelize seed files before running tests with

How do I do rake style commands in my test file (Jest) with sequelize seeder files?
I'm trying to do the same thing as this, but with sequelize.
describe('routes : movies', () => {
beforeEach(() => {
return knex.migrate.rollback()
.then(() => { return knex.migrate.latest(); })
.then(() => { return knex.seed.run(); });
});
afterEach(() => {
return knex.migrate.rollback();
});
});
I know I'm late to answer this but I just spent the past week trying to solve this issue. I have been able to successfully do this using Sequelize in conjunction with their sister project, Umzug. You will have to read the documentation for your specific issue but I can copy my test file so you can get an idea of how I did it. I'm happy to help someone if they still struggle with it after looking at the files.
// account.test.js
const models = require('../models/index.js');
const migrations = require("../index");
beforeAll(async () => {
await migrations.up().then(function() {
console.log("Migration and seeding completed")
});
});
afterAll( async () => {
await migrations.down().then(function() {
console.log("Migrations and down seeding completed");
})
const users = await models.User.findAll();
expect(users).toStrictEqual([]);
});
describe("Integration Test", () => {
it("Account integration test", async () => {
const data = { userId: 1210}
const users = await models.User.findAll();
console.log("All users:", JSON.stringify(users, null, 2));
expect(users[0].firstName).toBe('John');
expect(data).toHaveProperty('userId');
});
});
My index.js file
// index.js
const config = require('/config/config.json');
const { Sequelize } = require('sequelize');
const { Umzug, SequelizeStorage } = require('umzug');
const sequelize = new Sequelize(config);
const umzugMigration = new Umzug({
migrations: { glob: 'migrations/*.js' },
context: sequelize.getQueryInterface(),
storage: new SequelizeStorage({ sequelize }),
logger: console,
});
const umzugSeeding = new Umzug({
migrations: { glob: 'seeders/*.js' },
context: sequelize.getQueryInterface(),
storage: new SequelizeStorage({ sequelize }),
logger: console,
});
module.exports.up = () => umzugMigration.up().then(() => umzugSeeding.up());
module.exports.down = () => umzugSeeding.down();
I think you shouldn't make real DB requests while testing your code. Mock your DB request and return the data set from your mock function if it's needed. Otherwise, it looks like you testing a library, in your case this lib is knex.
Read for more details regarding mocks https://jestjs.io/docs/en/mock-functions

Categories

Resources