I can't create the pact-file, because the Query Path isn't correct - node.js

When I run the consumer part, Its get the following error:
1 failing
1) The Project API
"after each" hook for "returns the correct response":
Error: Pact verification failed - expected interactions did not match actual.
at new VerificationError (node_modules\#pact-foundation\pact\errors\verificationError.js:19:42)
at C:\Nexus\NovoTesteContrato\node_modules\#pact-foundation\pact\httpPact.js:102:23
at processTicksAndRejections (internal/process/task_queues.js:95:5)
And
Pact verification failed!
Actual interactions do not match expected interactions for mock MockService.
Missing requests:
GET /Project?Responsible=teste.k6%40k6.com&Name=Teste+para+a+pequisa
See C:/Nexus/NovoTesteContrato/logs/mockserver-integration.log for details.
My mock API and official API don't aceppt:
GET /Project?Responsible=teste.k6%40k6.com&Name=Teste+para+a+pequisa
My mock API and official API aceppt:
GET /Project?responsible=teste.k6%40k6.com&Name=Teste%20para%20a%20pequisa
How do I make PACT-JS send the request with "Test%20for%20a%20research" and not with "Test+for+the+research"?
My code is
import 'dotenv/config';
import { Matchers, Pact } from '#pact-foundation/pact';
import { eachLike, somethingLike, integer } from '#pact-foundation/pact/src/dsl/matchers';
import path from 'path';
import { GetProjectScenario1 } from '../../../api';
const mockProvider = new Pact({
consumer: 'TestProjectApi',
provider: 'Nexus',
log: path.resolve(process.cwd(), "__tests__/contract/logs", "pact.log"),
dir: path.resolve(process.cwd(), "__tests__/contract/pacts"),
logLevel: 'INFO',
pactfileWriteMode: 'overwrite',
spec: 2,
cors: true
});
let ProjectJsonSucessfull = ""
let responsibleSceario1 = "teste.k6#k6.com"
describe('Given - API TEST Nexus Project STAY ONLINE', () => {
beforeAll(async () => {
ProjectJsonSucessfull = require("./resources/tmp/Get_project_successfull_response.json")
})
describe('When I Search Project with sucessfull', () => {
beforeAll(async () =>
await mockProvider.setup().then(() => {
mockProvider.addInteraction({
uponReceiving: 'Only responsible',
withRequest: {
method: 'GET',
path: `/Project?Responsible=${responsibleSceario1}`
},
willRespondWith: {
status: 200,
headers: {
'Content-Type': 'application/json',
},
body: Matchers.like(ProjectJsonSucessfull).contents
}
});
})
);
afterEach(() => mockProvider.verify());
it('should return the expected data', async () => {
const response = await GetProjectScenario1(responsibleSceario1);
expect(response.headers['content-type']).toBe("application/json; charset=utf-8")
expect(response.status).toEqual(200);
expect(response.data).toEqual(ProjectJsonSucessfull);
});
})
afterAll(() => mockProvider.finalize())
})
Sed resquest with "/Project?responsible=teste.k6%40k6.com&Name=Teste%20para%20a%20pequisa"

Related

SvelteKit - can I consume a +server.ts endpoint from a store?

In my svelte website, I want to consume an endpoint inside a store, to fetch a list of servers for me to display in html divs. I cannot seem to understand how to call the API for me to fetch the servers.
from the serverSection component
(https://github.com/maxijabase/electricservers.com.ar/blob/master/src/components/serverSection.svelte)
src/components/serverSection.svelte
<script lang="ts">
export let bgImage: string
export let logo: string
export let text: string
import { fetchServers, serversStore } from '../stores/servers'
import Server from './server.svelte'
fetchServers()
</script>
<!-- some html -->
I'm trying to fetch a list of servers from an endpoint I created in a +server.ts file
(https://github.com/maxijabase/electricservers.com.ar/blob/master/src/routes/api/%2Bserver.ts)
this is src/stores/servers.ts
import { writable, type Writable } from 'svelte/store'
export const serversStore: Writable<any> = writable()
export const fetchServers = async () => {
const response = await fetch('/api', {
method: 'GET',
headers: {
'content-type': 'application/json',
accept: 'application/json',
},
})
serversStore.set(response)
}
this is src/routes/api/+server.ts
import type { RequestHandler } from './$types'
import { Server } from '#fabricio-191/valve-server-query'
import { serverList } from 'src/servers/serversList'
import { json } from '#sveltejs/kit'
export const GET: RequestHandler = async () => {
let infoList: Server.Info[] = []
for await (const server of serverList) {
const sv = await Server({ ip: server.ip, port: server.port, timeout: 3000 })
const svInfo = await sv.getInfo()
infoList.push(svInfo)
}
return json(infoList)
}
but I'm getting
Cannot read properties of undefined (reading 'length')
TypeError: Cannot read properties of undefined (reading 'length')
at Module.each (/node_modules/.pnpm/svelte#3.55.0/node_modules/svelte/internal/index.mjs:1841:31)
at eval (/src/components/serverSection.svelte:28:63)
at Object.$$render (/node_modules/.pnpm/svelte#3.55.0/node_modules/svelte/internal/index.mjs:1876:22)
at eval (/src/routes/+page.svelte:20:120)
at Object.$$render (/node_modules/.pnpm/svelte#3.55.0/node_modules/svelte/internal/index.mjs:1876:22)
at Object.default (root.svelte:41:38)
at eval (/src/routes/+layout.svelte:11:41)
at Object.$$render (/node_modules/.pnpm/svelte#3.55.0/node_modules/svelte/internal/index.mjs:1876:22)
at root.svelte:40:37
at $$render (/node_modules/.pnpm/svelte#3.55.0/node_modules/svelte/internal/index.mjs:1876:22)
C:\Users\Maxi\Documents\Programming\electricservers.com.ar\node_modules\.pnpm\undici#5.14.0\node_modules\undici\index.js:105
Error.captureStackTrace(err, this)
^
TypeError: Failed to parse URL from /api
at fetch (C:\Users\Maxi\Documents\Programming\electricservers.com.ar\node_modules\.pnpm\undici#5.14.0\node_modules\undici\index.js:105:13)
at async Module.fetchServers (/src/stores/servers.ts:8:20) {
[cause]: TypeError [ERR_INVALID_URL]: Invalid URL
at new NodeError (node:internal/errors:372:5)
at URL.onParseError (node:internal/url:553:9)
at new URL (node:internal/url:629:5)
at new Request (C:\Users\Maxi\Documents\Programming\electricservers.com.ar\node_modules\.pnpm\undici#5.14.0\node_modules\undici\lib\fetch\request.js:78:21)
at fetch (C:\Users\Maxi\Documents\Programming\electricservers.com.ar\node_modules\.pnpm\undici#5.14.0\node_modules\undici\lib\fetch\index.js:136:21)
at fetch (C:\Users\Maxi\Documents\Programming\electricservers.com.ar\node_modules\.pnpm\undici#5.14.0\node_modules\undici\index.js:103:20)
at Module.fetchServers (/src/stores/servers.ts:8:26)
at eval (/src/components/serverSection.svelte:19:24)
at Object.$$render (/node_modules/.pnpm/svelte#3.55.0/node_modules/svelte/internal/index.mjs:1878:22)
at eval (/src/routes/+page.svelte:20:120) {
input: '/api',
code: 'ERR_INVALID_URL'
}
}
 ELIFECYCLE  Command failed with exit code 1.
I have no idea how to do this properly

Angular Universal SSR loading static assets in prerender stage

I'm looking for an approach to accessing assets in the /assets/ folder that is used to build the content in a component when prerendering an application. I'm using Angular 14 and the #nguniversal/express-engine package. I can't seem to get static assets to be read in the app when running npm run prerender.
I've seen the discussion at #858 however as the last comment points out this won't work when prerendering.
I have a minimal example of what I mean here:
https://stackblitz.com/edit/angular-ivy-dxb32y?file=src%2Fapp%2Fapp.service.ts
You see my service turns the path into an absolute URL:
public getContents(path: string): Observable<string> {
if (isPlatformServer(this.platformId) && path.includes('./')) {
path = `http://localhost:4200/${path.replace('./', '')}`
}
return this.http.get(path, {
observe: 'body',
responseType: 'text',
});
}
And the ssr:dev command serves this content correctly.
However, under prerender I get the following error:
⠸ Prerendering 1 route(s) to C:\Users\***\preloading\dist\preloading\browser...ERROR HttpErrorResponse {
headers: HttpHeaders {
normalizedNames: Map(0) {},
lazyUpdate: null,
headers: Map(0) {}
},
status: 0,
statusText: 'Unknown Error',
url: 'http://localhost:4200/assets/file.txt',
ok: false,
name: 'HttpErrorResponse',
message: 'Http failure response for http://localhost:4200/assets/file.txt: 0 Unknown Error',
I've tried a few things, such as:
Turning the relative URLs into absolute URLs (https://github.com/angular/universal/issues/858) however this doesn't work during prerender
Using fs to read the static assets however these node modules can't be found during the prerender stage:
if (isPlatformServer(this.platformId) && path.includes('./')) {
import("fs")
path = `http://localhost:4200/${path.replace('./', '')}`
}
Gives:
✔ Browser application bundle generation complete.
⠦ Generating server application bundles (phase: sealing)...
./src/app/app.service.ts:14:8-20 - Error: Module not found: Error: Can't resolve 'fs' in 'C:\Users\***\preloading\src\app'
Error: src/app/app.service.ts:12:14 - error TS2307: Cannot find module 'fs' or its corresponding type declarations.
12 import("fs")
Any other ideas at all about what I can do?
So I managed to crack this using the relatively hacky solution of running both ng serve and npm run prerender using a node script:
https://stackblitz.com/edit/angular-ivy-uy7wy9?file=prerender.js
var error = false;
function sleep(miliseconds) {
console.log(`Sleeping for ${miliseconds} ms`);
if (miliseconds == 0)
return Promise.resolve();
return new Promise(resolve => setTimeout(() => resolve(), miliseconds))
}
async function run() {
try {
console.log("Running Angular server");
var proc = require('child_process').spawn('ng', ['serve']);
await sleep(20000)
console.log("Running prerender");
var prerender = require('child_process').spawn('npm', ['run', 'prerender']);
var prerenderTimeoutSeconds = 120;
var timeoutObject;
var timeoutResolve;
var timeoutReject;
var timeout = new Promise((resolve, reject) => {
timeoutResolve = resolve;
timeoutReject = reject;
timeoutObject = setTimeout(() => {
console.log('Timed out, killing prerender');
try {
prerender.kill("SIGKILL")
reject(Error("Timed out running prerender"))
} catch (e) {
console.error(e)
reject(Error('Cannot kill prerender'));
}
}, prerenderTimeoutSeconds * 1000)
});
prerender.stdout.on('data', (data) => {
console.log(`prerender stdout: ${data}`);
});
prerender.stderr.on('data', (data) => {
console.error(`prerender stderr: ${data}`);
});
prerender.on('close', (code) => {
clearTimeout(timeoutObject);
console.log(`prerender exited with code ${code}`)
if (code === 0) {
timeoutResolve()
} else {
timeoutReject(Error(`prerender exited with code ${code}`));
}
});
await timeout
} catch (err) {
console.error(err);
console.error(err.stack);
error = true;
} finally {
if (proc) {
console.log("Killing Angular server");
var angularKilled = proc.kill("SIGKILL")
console.log(`kill -9 on Angular success [${angularKilled}]`)
}
}
}
(async () => await run())();
if (error) {
throw new Error("Exception during execution")
}

MSW v0.40 Error: thrown: Exceeded timeout of 5000 ms for a test

I've been using MSW since v0.35.0. Recently I updated it to v0.40.1 and now it seems like MSW is not intercepting the request to the servers and I'm getting the following error.
Here is my test code.
import axios from 'axios';
import { rest } from 'msw';
import { setupServer } from 'msw/node';
const path = 'login/';
const accessToken = 'AccessTokenValue';
const correctCredential = { email: 'test#email.com', password: 'password' };
const server = setupServer(
rest.post(path, (req, res, ctx) => {
return res(ctx.status(200), ctx.json({ data: { access: accessToken } }));
}),
);
beforeAll(() => server.listen());
afterAll(() => server.close());
afterEach(() => server.resetHandlers());
describe('Login', () => {
test('Case: Success', async () => {
let token = '';
await axios
.post('https://test.com' + path, correctCredential)
.then((response) => (token = response.data.data.access));
expect(token).toBe(accessToken);
});
});
And this is the error I get.
Error: Request failed with status code 400
at createError (<my_local_path>)
at settle (<my_local_path>)
at IncomingMessage.handleStreamEnd (<my_local_path>)
at IncomingMessage.emit (node:events:402:35)
at endReadableNT (node:internal/streams/readable:1343:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21)
Here are the versions of the other packages I use.
jest: 27.0.6
axios: 0.25.0
I read Examples from MSW and I don't see any problem with my implementation.
Perhaps this issue is relevant.
https://github.com/mswjs/msw/issues/1125
This issues was fixed 5 days ago, so I believe a corrected version will be released in the near future.
btw, downgrading to 0.36.8 is temporary solution.

Hapi.js Cannot read property 'statusCode' of null

I'm creating a node.js api server using hapi.js and mongodb and I'm having some trouble to get it working on Amazon EC2.
Running it locally works, but if I run it on an EC2 instance I'm getting the error TypeError: Cannot read property 'statusCode' of null
The complete stacktrace is the following:
TypeError: Cannot read property 'statusCode' of null
at Request._finalize (/home/ec2-user/backend/node_modules/#hapi/hapi/lib/request.js:497:31)
at Request._reply (/home/ec2-user/backend/node_modules/#hapi/hapi/lib/request.js:434:18)
at Request._execute (/home/ec2-user/backend/node_modules/#hapi/hapi/lib/request.js:280:14)
at processTicksAndRejections (node:internal/process/task_queues:93:5)
The strange part is that GET requests are working while PUT, POST and DELETE are throwing the above error.
I've setup the server.js as follow:
...
const init = async () => {
const server = Hapi.server({
port: 3000,
});
//server.route(routes);
server.route([
{
method: "GET",
path: "/test",
handler: async (request, h) => {
return "workin GET";
},
},
{
method: "PUT",
path: "/test",
handler: async (request, h) => {
return "workin PUT";
},
},
{
method: "POST",
path: "/test",
handler: async (request, h) => {
return "workin POST";
},
},
{
method: "DELETE",
path: "/test",
handler: async (request, h) => {
return "workin DELETE";
},
},
]);
await server.start();
console.log('Server running on %s', server.info.uri);
};
process.on('unhandledRejection', (err) => {
console.log(err);
process.exit(1);
});
init();
Any solution?
I've found out that on the EC2 instance I had installed node version 15.5.0 which apparently is not compatible with the latest version of hapi.js (20.0.2).
To fix the issue just install node version 14.15.3.
This is fixed in #hapi/hapi v20.2.1: https://github.com/hapijs/hapi/issues/4319.
Just remove #hapi/hapi and re-install it

Node e2e tests - async beforeEach/afterEach hooks fail on Windows

On OSX and Linux, the following works great (this is as simplified a reproduction as possible, hopefully without sacrificing meaning):
import { expect } from 'chai';
import { MongoClient, Db } from 'mongodb';
import { Application, Request } from 'express';
import { Server } from 'http';
import * as config from 'config';
describe('some test', () =>
{
let Session:{ new(app:Application):Request } = require('supertest-session'),
app:Application,
server:Server,
mongoClient:MongoClient,
db:Db;
beforeEach(async () =>
{
app = express();
server = app.listen(config.Http.port);
request = new Session(app);
// On Windows tests are executed before this resolves
mongoClient = await MongoClient.connect(config.Database.connectionOptions.url);
db = mongoClient.db(config.Database.connectionOptions.database);
});
afterEach(async () =>
{
await db.dropDatabase();
request.destroy();
server.close();
});
it('works like it oughtta', () =>
{
request.post('/api/account/login')
.send({ email: 'me#example.com', password: 'password' })
.expect(200)
.then((res) =>
{
expect(res.success).to.eq(true);
})
})
});
On a Windows machine, the above fails with the following output from npm:
13 verbose stack Exit status 4
13 verbose stack at EventEmitter.<anonymous> (C:\Path\To\AppData\Roaming\nvm\v9.4.0\node_modules\npm\node_modules\npm-lifecycle\lib\index.js:285:16)
... rest of stack
13 verbose stack at Process.ChildProcess._handle.onexit (internal/child_process.js:220:5)
If I take the database connection out of the beforeEach hook and do this instead, the test will run and pass, but I still notice hard-to-track-down failures in further tests with async hooks:
before(function(done)
{
MongoClient.connect(function(err, client)
{
mongoClient = client;
done();
});
});
after(function(done)
{
mongoClient.close(function() { done(); });
});
I've seen this behavior using Mocha, Jest and FuseBox test runners. Running node#9.4 on both machines. The solution to this cannot be "just make sure I test my tests on a Windows machine before I push".

Resources