My issue: The console.log('tableNobject: ', tableNobject) does not log in knex migration.
The following code is what I have tried:
// solution A
export async function up(knex: Knex) {
const tableAobject = await knex.select('*').from('tableAobject');
console.log('tableAobject: ', tableAobject);
}
// solution B
export async function up(knex: Knex) {
await knex.select('*').from('tableBobject').then((tableBobject) => {
console.log('tableBobject: ', tableBobject);
});
}
However my terminal output is the following:
Migration Starting ...
Migrated
Migration Done.
These logs come from our migration script where we call database.migrate.latest()
My expected terminal output for the code above would be something like this:
Migration Starting ...
tableNobject: [
{
id: 'randomId'
someData: 'someDataString'
...
},
...
]
Migrated
Migration Done.
I know logging tables that you get from knex is possible because when I set up a test script outside the migration flow I can log the table without issues.
I have tried the following addition of settings:
const configA = {
...
debug: true,
}
const configB = {
...
log: {
warn(message) {
console.log(message)
},
error(message) {
console.log(message)
},
deprecate(message) {
console.log(message)
},
debug(message) {
console.log(message)
},
}
}
const configC = {
...
debug: true,
log: {
warn(message) {
console.log(message)
},
error(message) {
console.log(message)
},
deprecate(message) {
console.log(message)
},
debug(message) {
console.log(message)
},
}
};
The different settings above dont give me the logging in the terminal as I want.
The base settings (I dont know if this gives an added value):
const config = {
client: 'postgresql',
connection: {
host: '127.0.0.1',
port: '5432',
database: 'projectName_develop',
user: 'user',
password: 'dev',
},
pool: {
min: 2,
max: 10,
},
migrations: {
tableName: 'knex_migrations',
directory: path.join(__dirname, 'migrations'),
},
seeds: {
directory: path.join(__dirname, 'seeds'),
},
asyncStackTraces: true,
};
So the reason why my console.log didnt log was because the migrations are TypeScript files.
I forgot to run the command: npm run build-ts-backed:watch
So the solution was easier than the issue at hand. Please remember to run your TypeScript compiler when you test in TypeScript.
Related
I'm using cypress + multiple-cucumber-html-report to generate a report after execution. There is the possibility to add custom data to the report such as execution start and end time.
I assume this information somehow comes from cypress as part of the result meta data.
I tried to put results in json file after the run finishes, by adding it to the cypress config file:
import { defineConfig } from 'cypress';
import * as fs from 'fs';
async function setupNodeEvents(on, config) {
on('after:run', async (results) => {
if (results) {
fs.mkdirSync("cypress/.run", { recursive: true });
fs.writeFile("cypress/.run/results.json", JSON.stringify(results), (err) => {
if (err)
console.log(err);
else {
console.log("Successful results has been written");
}
});
}
})
return config;
}
export default defineConfig({
e2e: {
setupNodeEvents,
experimentalInteractiveRunEvents: true
},
});
then read these results in the report generation file:
const report = require('multiple-cucumber-html-reporter');
const fs = require('fs');
fs.readFile('cypress/.run/results.json', function read(err, data) {
if (err) {
throw err;
}
var runInfos = JSON.parse(data);
report.generate({
jsonDir: './cypress/result/',
reportPath: './cypress/report/',
metadata:{
browser: {
name: runInfos.browserName,
version: runInfos.browserVersion
},
device: 'Cypress',
platform: {
name: mapOs(runInfos.osName)
}
},
customData: {
title: 'Run info',
data: [
{label: 'Project', value: 'project'},
{label: 'Execution Start Time', value: new Date(runInfos.startedTestsAt).toLocaleString()},
{label: 'Execution End Time', value: new Date(runInfos.endedTestsAt).toLocaleString()}
]
}
});
});
unfortunately the after:run was never triggered, and not even throwing an error.
Take a look at the docs on After Run API
When running via cypress open, the after:run event only fires if the experimentalInteractiveRunEvents flag is enabled.
Unfortunately, from the look of your config sample you must be using an older version of Cypress (pre v10).
To make this more useful, upgrade Cypress the use the flag mentioned above like this:
// cypress.config.js
const { defineConfig } = require('cypress')
module.exports = defineConfig({
// setupNodeEvents can be defined in either
// the e2e or component configuration
e2e: {
setupNodeEvents(on, config) {
on('after:run', (results) => {
/* ... */
})
},
experimentalInteractiveRunEvents: true, // here is the flag, not documented in the configuration page
},
})
I am trying to schedule cronjobs which will run at specified time, i am using hapi-cron-job of hapi, when i try to register the plugin, i am getting below error.
[1] "plugin.register" must be of type function
at Object.exports.apply (D:\my_dir\Repositories\repo-cronjobs\node_modules\#hapi\hapi\lib\config.js:19:15)
at internals.Server.register (D:\my_dir\Repositories\repo-cronjobs\node_modules\#hapi\hapi\lib\server.js:454:31)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
Please find the configuration while registering the plugin.
server.js
const { plugins } = require('./register/index');
await server
.register(plugins)
.then(() => {})
.catch(err => {
console.error('Plugin registeration failed!');
console.error(err);
});
index.js
module.exports.plugins = [
// I have here other pluguns, passing this array for registration in server.js
require("./hapi-cron-job-plugin")
];
hapi-cron-job-plugin.js
const hapiCronJob = require('hapi-cron-job')
const plugin = {
register: require('hapi-cron-job'),
options: {
jobs: [
{
name: "diplay time",
enabled: true,
immediate: true,
schedule: "every 1 s",
execute: alertSystemAdminAndDispatcher,
environments: ['development', 'staging']
}
],
}
}
module.exports = plugin;
nodeJS version: v14.17.3
Hapi-cron-job: "hapi-cron-job": "^2.0.1"
i'm not really good at English and beginner of coding. i use javascript and my OS is Mac.
Anyway, i wrote row query in MysqlWorkbench and now, i want to write it in VScode to sequelize.
select reservation_datetime
from LectureReservation
Inner Join Lecture
On LectureReservation.lecture_id = Lecture.id
Where Lecture.mentor_id = 1
this is my query and
module.exports = {
get: (req, res) => {
if (req.params.id) {
LectureReservation
.findOne({
include: [
{
model: Lecture,
where: {
Lecture_id: Lecture.id,
},
},
],
attributes: ['reservation_datetime'],
where: {
mentor_id: req.params.id,
},
})
.then((result) => {
if (result) {
res.status(200).json({ message: 'OK!' });
} else {
res.status(409).json({ message: 'Wrong Access' });
}
})
.catch((err) => {
res.status(500).send(err);
});
}
},
};
this is my sequelize code. and
this is my err code in postman..
Result: How can I edit my sequelize code to fix my postman err..?
It seems this is not a sequelize related error. The error code is 404. Which means the route is not available. Please check your routes.
Also you don't need to specify the include condition if your sequelize models associated properly. You can just write
include: [
{
model: Lecture
},
],
Expected: Running npm run pactTest should generate a pact file (JSON).
Results: I get an Unable to connect error.
Pact.io JavaScript implementation guide.
Pact.io Typescript test example.
Appreciate any thoughts or ideas as to what I'm doing wrong :)
The Error
FAIL src/services/api/TotalPayout.test.pact.ts
The API
getUsersTotalPayout
✕ Should call getUsersTotalPayout and return an object with the total_payout (45ms)
● The API › getUsersTotalPayout › Should call getUsersTotalPayout and return an object with the total_payout
PopsicleError: Unable to connect to "http://127.0.0.1:12345/interactions"
Caused by: Error: connect ECONNREFUSED 127.0.0.1:12345
at Request.Object.<anonymous>.Request.error (node_modules/popsicle/src/request.ts:91:12)
at ClientRequest.<anonymous> (node_modules/popsicle/src/index.ts:218:31)
package.json script:
"pactTest": "export NODE_ENV=pactTest && jest --testRegex \"/*(.test.pact.ts)\" --runInBand --setupFiles ./pactSetup.ts --setupTestFrameworkScriptFile ./pactTestWrapper.ts",
My src/pactSetup.ts file
// #ts-ignore
import path from 'path';
import { Pact } from '#pact-foundation/pact/pact';
// #ts-ignore
global.provider = new Pact({
port: 1234,
log: path.resolve(process.cwd(), 'logs', 'mockserver-integration.log'),
dir: path.resolve(process.cwd(), 'pacts'),
spec: 2,
cors: true,
pactfileWriteMode: 'update',
consumer: 'Exchange',
provider: 'LP Service'
});
My src/pactTestWrapper.ts
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; // This is to give the pact mock server time to start
// #ts-ignore
beforeAll(() => provider.setup()); // Create mock provider
// #ts-ignore
afterEach(() => provider.verify()); // Ensure the mock provider verifies expected interactions for each test
// #ts-ignore
afterAll(() => provider.finalize()); // Tear down the mock and write the pact
The test: src/services/api/TotalPayout.test.pact.ts
// #ts-ignore
import path from 'path';
import { Pact } from '#pact-foundation/pact';
import { getTotalPayout } from './apiPayout';
const port = 12345;
const endpoint = '/frontoffice/api/get-total-payout';
const EXPECTED_BODY = {
total_payout: 100.21,
};
const userId = 'foo';
const provider = new Pact({
port,
log: path.resolve(process.cwd(), 'logs', 'mockserver-integration.log'),
dir: path.resolve(process.cwd(), 'pacts'),
spec: 2,
consumer: 'Exchange',
provider: 'LP Service',
pactfileWriteMode: 'merge'
});
describe('The API', () => {
// Copy this block once per interaction under test
describe('getUsersTotalPayout', () => {
beforeEach(() => {
const interaction = {
uponReceiving: 'a GET request with a user id',
withRequest: {
method: 'GET',
path: endpoint,
headers: {
Accept: 'application/json',
},
},
willRespondWith: {
status: 200,
headers: {
'Content-Type': 'application/json'
},
body: EXPECTED_BODY
},
};
// #ts-ignore
return provider.addInteraction(interaction);
});
// add expectations
it('Should call getUsersTotalPayout and return an object with the total_payout', done => {
getTotalPayout(userId)
.then((response: any) => {
expect(response).toEqual(EXPECTED_BODY);
})
.then(done);
});
});
});
The api service file apiPayout.ts
// #ts-ignore
import axios, * as others from 'axios';
const endpoint = '/frontoffice/api/';
export const getTotalPayout = async (userId: string) => {
const response = await axios.get(`${endpoint}get-total-payout`, { params: userId });
return response.data;
};
From the mockserver-integration.log
I, [2018-09-19T11:07:41.259437 #79922] INFO -- : Verifying - interactions matched
I, [2018-09-19T11:07:41.264440 #79922] INFO -- : Cleared interactions
From the debug-log
20 error code ELIFECYCLE
21 error errno 1
22 error react-redux-starter-kit#1.0.0 pactTest: `export NODE_ENV=pactTest && jest --testRegex "/*(.test.pact.ts)" --runInBand --setupFiles ./pactSetup.ts --setupTestFrameworkScriptFile ./pactTestWrapper.ts`
22 error Exit status 1
23 error Failed at the react-redux-starter-kit#1.0.0 pactTest script.
Update
After commenting out the provider setup logic in the test.pact file and re-running npm run pactTest I get the following:
console.error node_modules/#pact-foundation/pact/pact.js:110
Pact verification failed!
console.error node_modules/#pact-foundation/pact/pact.js:111
Actual interactions do not match expected interactions for mock MockService.
Missing requests:
GET /frontoffice/api/liquidity-pool/get-total-payout
See /Users/leongaban/projects/trade.io/tradeio-front/logs/mockserver-integration.log for details.
And my updated mockserver-intergration.log
I, [2018-09-19T14:12:19.128823 #82330] INFO -- : Registered expected interaction GET /frontoffice/api/liquidity-pool/get-total-payout
D, [2018-09-19T14:12:19.129127 #82330] DEBUG -- : {
"description": "a GET request with a user id",
"request": {
"method": "GET",
"path": "/frontoffice/api/liquidity-pool/get-total-payout",
"headers": {
"Accept": "application/json"
}
},
"response": {
"status": 200,
"headers": {
"Content-Type": "application/json"
},
"body": {
"total_payout": 100.21
}
}
}
W, [2018-09-19T14:12:19.139198 #82330] WARN -- : Verifying - actual interactions do not match expected interactions.
Missing requests:
GET /frontoffice/api/liquidity-pool/get-total-payout
W, [2018-09-19T14:12:19.139254 #82330] WARN -- : Missing requests:
GET /frontoffice/api/liquidity-pool/get-total-payout
Several issues I can point out:
You seem to be declaring and spinning a pact mock server twice: in the src/pactSetup.ts file and also in TotalPayout.test.pact.ts which I'm not sure it's what you intended to do. You probably want to avoid declaring the provider in the TotalPayout test, and instead you already have the provider object on the global scope as part of the test framework setup files.
In the code apiPayout.ts you are referring to the endpoint URL, but to which port is it sending the request? This API call should be ultimately caught by the pact mock provider that you are spinning up. If you call to a different port than what the mock provider is listening on you'll never hit it.
A small nitpick: /frontoffice/api/get-total-payout is not a RESTful. You want to avoid including verbs such as "get" in your API and use the proper HTTP method for that (GET).
Not sure if that was your problem, but I had the order of writePact and finalize wrong. I had:
afterAll(async () => {
await provider.finalize()
await provider.writePact()
})
instead of the correct order:
afterAll(async () => {
await provider.writePact()
await provider.finalize()
})
I'm having mocha tests with project that uses knex pool.
The issue I have is when test ends, it keep waiting until knex pool is drained, and it takes extra seconds (about 5-10) to finish mocha run.
Code example:
knex initialized:
const Knex = require('knex');
const knex = new Knex({
client: 'pg',
pool: { min: 1, max: 10 },
connection: {},
searchPath: 'knex,public',
// debug: true,
});
Mocha test drains connection:
after((done) => {
knex.destroy().then(done);
})
What I would like to accomplish is any of both:
drain knex connections faster
somehow mocha finish test without waiting knex draining
Any suggestions?
This functionality changed while ago in mocha
2879: By default, Mocha will no longer force the process to exit once all tests complete. This means any test code (or code under test)
which would normally prevent node from exiting will do so when run in
Mocha. Supply the --exit flag to revert to pre-v4.0.0 behavior
(#ScottFreeCode, #boneskull)
https://github.com/mochajs/mocha/blob/master/CHANGELOG.md
If the above doesn't help you can always call process.exit(0) in done to force killing the process with success exit code.
AFAIK in knex side there is no force options for force killing the connections.
This will help your connection from draining.
const config = {
client: "pg",
connection: {
host: hostname,
user: username,
password: password,
database: datbase
},
pool: {
min: 0,
max: 10
},
acquireConnectionTimeout: 1000
}
var Knex = require('knex')
this.functioname = () => {
var output = {}
return new Promise(function (resolve) {
var knex = new Knex(config)
knex(tablename)
.select()
.then((result) => {
if (result.length > 0) {
output.error = false
output.result = result
} else {
output.error = true
}
resolve(output)
})
.catch((err) => {
err.error = true
resolve(err)
})
.finally(() => {
knex.destroy()
})
})
}