Error: Fixture "activityLogPage" has unknown parameter "TestRailController" - javascript

I have a bit of code here that keeps failing due to Error: Fixture "activityLogPage" has unknown parameter "TestRailController", I am sure this is user error on my end but I cant quite figure it out. Below this is the TestRailController I am trying to call.
activitylogpage.ts --->
import { ActivityLogSelectors } from '../../specs/types/activityLog.type';
import { Page } from '#playwright/test';
import test from '../../common/testrail/fixtures';
export const activityLogSelectors: ActivityLogSelectors = {
datasource_id: 'label[for^=datasource_id]',
categories: 'label:has-text("Access Control: Authentication")',
policy: 'input[id^=downshift]',
};
type ActivityLogFixtures = {
activityLogPage: Page;
};
const activityLogTest = test.extend<ActivityLogFixtures>({
activityLogPage: async ({ page, TestRailController }, use) => {
TestRailController.startNewTest('1');
await page.goto('/');
await page.waitForURL(/risk-posture/i);
await page.click('a:has-text("Activity Log")');
await page.waitForSelector('text=Clear');
await use(page);
},
});
export default activityLogTest;
fixtures.js. --->
const base = require('#playwright/test');
const TestRailController = require('./testrail.interface.js');
module.exports = base.test.extend({
// https://playwright.dev/docs/test-advanced/#testinfo-object
testrailController: async ({ browser }, use, testInfo) => {
const testrailController = new TestRailController();
await use(testrailController);
for (const context of browser.contexts()) {
// eslint-disable-next-line no-await-in-loop
await context.close();
}
// only update testrail when process.env.APP_VERSION is valid string
// testInfo is needed here because this below part will be run before test started while testInfo is null
// use testrail feature for saving test-result
if (appVersion && testInfo) {
await testrailController.updateAllTests(testInfo);
} else {
console.log('Env var APP_VERSION or testInfo is not available, will not update testrail case');
}
},
});

Related

How to dynamically import module for nitro on nuxt app

Im trying to dynamically load modules from a nitro server in a nuxt app, but I get the following error:
Cannot find module projectpath/.nuxt/services/listing imported from projectpath/.nuxt/dev/index.mjs
This is the snippet of code Im using for the handler where the dynamic import should take place:
export default defineEventHandler(async (event) => {
const { method, resource, paramValue } = parseRequestResource(event.node.req)
let ServiceInstance = services[resource]
if (ServiceInstance) {
return callResourceMethod(ServiceInstance, method, paramValue, event)
} else {
try {
ServiceInstance = await import(`../services/${resource}`)
} catch (error) {
const Proto = Object.assign({}, Service.prototype, { tableName: resource })
ServiceInstance = Object.create(Proto)
services[resource] = ServiceInstance
}
return callResourceMethod(ServiceInstance, method, paramValue, event)
}
})
How can I this to work? Is there some feature that nitro/nuxt have where I can do this?
I was able to achieve this functionality by using a nitro plugin. However the files being imported need to be *.mjs.
import fs from 'fs'
import { resolve } from 'path'
export default defineNitroPlugin(async (nitroApp) => {
const __dirname = resolve()
const servicesFolderPath = `${__dirname}/server/services`
const serviceFiles = fs.readdirSync(servicesFolderPath)
const services = {}
for (const fileName of serviceFiles) {
if (fileName == '__proto__.mjs') continue
try {
const moduleName = fileName.split('.')[0]
const module = await import(`${servicesFolderPath}/${fileName}`)
services[moduleName] = module.default
} catch (error) {
console.log(error);
}
}
nitroApp.$services = services
})

Nextjs getting build time error Cannot read properties of undefined

I am not getting any error when browsing page or url but when trying to npm run build getting this error Generating static pages (0/8)TypeError: Cannot read properties of undefined (reading 'blog_slug')
here is my full code:
I aslo want to show 404 page if dynamic url not exits. Right now I am getting this error for invalid url . I also set
if (res != 200) {
return {
notFound: true,
};
}
but didn't work. here is my full code:
export async function getStaticPaths() {
const search_url = "https://backendapi.mydomain.com/blog-list/";
const search_result = await fetch(search_url);
const search_data = await search_result.json(search_result);
const paths = search_data.map((data) => {
return {
params: {
id: data.blog_slug,
},
};
});
return {
paths,
fallback: true, // false or 'blocking'
};
}
export async function getStaticProps(context) {
const id = context.params.id;
const res = await fetch(`https://mydomain/blog-api/${id}`);
const Blog = await res.json();
const search_url = "https:/mydomain/blog-list/";
const search_result = await fetch(search_url);
const search_data = await search_result.json(search_result);
if (res != 200) {
return {
notFound: true,
};
}
return {
props: {
data: Blog,
search_data: search_data,
},
};
}
here is my jsx look like:
function blog_details({ data, search_data }) {
return (<h1>data.blog_slug<h1/)
}

How to initialize App Data in node js and access it without being undefined in jest test?

i am initializing a node js app with crucial data for the app to work from a database in index.js.
index.ts
import {getInitialData} from 'initData.ts';
export let APP_DATA: AppData;
export const initializeAppData = async () => {
try {
APP_DATA = (await getInitialData()) as AppData;
if (process.env.NODE_ENV !== 'test') {
initializeMongoose();
startServer();
}
} catch (error) {
console.log(error);
}
};
initData.ts
let dbName: string = 'initialData';
if (process.env.NODE_ENV === 'test') {
dbName = 'testDb';
}
const uri = `${process.env.MONGODB_URI}/?maxPoolSize=20&w=majority`;
export async function getInitialData() {
const client = new MongoClient(uri);
try {
await client.connect();
const database = client.db(dbName);
const configCursor = database
.collection('config')
.find({}, { projection: { _id: 0 } });
const config = await configCursor.toArray();
const aaoCursor = database
.collection('aao')
.find({}, { projection: { _id: 0 } });
const aao = await aaoCursor.toArray();
return { config, aao };
} catch {
(err: Error) => console.log(err);
} finally {
await client.close();
}
}
I'm using this array in another file and import it there.
missionCreateHandler
import { APP_DATA } from '../index';
export const addMissionResources = (
alarmKeyword: AlarmKeyword,
newMission: MissionDocument
) => {
const alarmKeywordObject = APP_DATA?.aao.find(
(el) => Object.keys(el)[0] === alarmKeyword
);
const resourceCommand = Object.values(alarmKeywordObject!);
resourceCommand.forEach((el) => {
Object.entries(el).forEach(([key, value]) => {
for (let ii = 1; ii <= value; ii++) {
newMission.resources?.push({
initialType: key,
status: 'unarranged',
});
}
});
});
};
I'm setting up a mongodb-memory-server in globalSetup.ts for Jest and copy the relevant data to the database from json-files.
globalSetup.ts
export = async function globalSetup() {
const instance = await MongoMemoryServer.create({
instance: { dbName: 'testDb' },
});
const uri = instance.getUri();
(global as any).__MONGOINSTANCE = instance;
process.env.MONGODB_URI = uri.slice(0, uri.lastIndexOf('/'));
process.env.JWT_SECRET = 'testSECRET';
const client = new MongoClient(
`${process.env.MONGODB_URI}/?maxPoolSize=20&w=majority`
);
try {
await client.connect();
const database = client.db('testDb');
database.createCollection('aao');
//#ts-ignore
await database.collection('aao').insertMany(aao['default']);
} catch (error) {
console.log(error);
} finally {
await client.close();
}
};
missionCreateHandler.test.ts
test('it adds the correct mission resources to the array', async () => {
const newMission = await Mission.create({
address: {
street: 'test',
houseNr: 23,
},
alarmKeyword: 'R1',
});
const expected = {
initialType: 'rtw',
status: 'unarranged',
};
addMissionResources('R1', newMission);
expect(newMission.resources[0].initialType).toEqual(expected.initialType);
expect(newMission.resources[0].status).toEqual(expected.status);
});
When runing the test, i get an 'TypeError: Cannot convert undefined or null to object at Function.values ()'. So it seems that the APP_DATA object is not set. I checked that the mongodb-memory-server is set up correctly and feed with the needed data.
When i hardcode the content of APP_DATA in index.ts, the test runs without problems.
So my questions are: How is the best practice to set up initial data in a node js app and where to store it (global object, simple variable and import it in the files where needed)? How can the test successfully run, or is my code just untestable?
Thank you!

The test with JestJS that closes the application does not work

Friends, I have a problem!
I'm testing my API with NestJS.
I'm using Jest for the test. Unfortunately, I am encountering the following error:
TypeError: Cannot read properties of undefined (reading 'close')
This error is very explicit but I don't see where it could come from.
Would you have an idea?
My current code :
import * as pactum from 'pactum';
import { Test } from '#nestjs/testing';
import { AppModule } from '../src/app.module';
import { INestApplication, ValidationPipe } from '#nestjs/common';
import { PrismaService } from '../src/prisma/prisma.service';
import { AuthDto } from '../src/auth/dto';
describe('App e2e', () => {
let app: INestApplication;
let prisma: PrismaService;
beforeAll(async () => {
const moduleRef = await Test.createTestingModule({
imports: [AppModule],
}).compile();
const app = moduleRef.createNestApplication();
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
}),
);
await app.init();
await app.listen(3334);
prisma = app.get(PrismaService);
await prisma.cleanDatabase();
});
afterAll(async () => {
console.log('Closing server');
await app.close(); // <------------- THE PROBLEM ARISES HERE.
});
describe('Auth', () => {
describe('Signup', () => {
it('should signup a user', () => {
const dto: AuthDto = {
email: 'darrel.doe#mail.com',
password: '1234',
};
return pactum
.spec()
.post('http://localhost:3333/auth/signup')
.withBody(dto)
.expectStatus(201);
});
});
describe('Signin', () => {
it.todo('should signin a user');
});
});
});
You are mixing two variables in different scopes.
let app: INestApplication; is upper scope one which you are actually using, since it does not have any value assigned it is undefined. The inner one is different because you are defining inside another scope.
A solution is very simple, just remove const from const app = moduleRef.createNestApplication();

Nextjs getStaticPaths not generating paths in build time with dynamic routes

I am trying to go to /users/0 from /users page.
In /users/[id].js
export async function getStaticProps(context) {
const { params } = context;
const { id } = params.id;
const transformedUsers = await getData();
const foundUser = transformedUsers.find((user) => user.id === id);
if (transformedUsers.length === 0) {
return {
notFound: true,
};
}
return {
props: {
user: foundUser,
},
};
}
export async function getStaticPaths() {
const transformedUsers = await getData();
const ids = transformedUsers.map((user) => user.id);
const pathsWithParams = ids.map((id) => ({ params: { id } }));
return {
paths: pathsWithParams,
fallback: false,
};
}
After I run the commands npm run build
└ ● /users/[id] 298 B 82.4 kB
I am getting this in the console. But when I start the server with npm start and go to /users/0 i am getting 404 not found.
How to provide paths with getStaticPaths?

Categories