Typescript: classes and Interfaces in definition file getting required in compiled .js - node.js

I have a Typescript project with two important files:
app.ts
models.d.ts
The first few lines of app.ts look like this:
///<reference path="models.d.ts"/>
'use strict';
import * as fs from 'async-file';
import { MyClass } from './models';
The first few lines of the compiled app.js are:
///<reference path="models.d.ts"/>
'use strict';
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs = require("async-file");
const models_1 = require("./models"); //// ERROR THROWN HERE!!!!!!!!
However, no models.js is generated because it's just a .d.ts declaration file. So when I run this, and require is called to get ./models, I get the following exception:
Cannot find module './models'
This is Visual Studio Professional 2017 and I don't have a tsconfig.json file. However, my project compilation settings look like this:
What am I doing wrong? This is killing me.

models.d.ts implies that there is a models.js that already exists in its place in your output directory.
You should probably use a .ts file if that isn't the case. In other words, rename it from models.d.ts to models.ts.

Related

How to write the unit test for 'fs unlink' using vitest for the follow function?

deleteDuplicatedImage.ts
import { unlink, PathLike } from "fs";
import { logger } from "../libraries";
export const deleteDuplicatedImage = (imagePath: PathLike) => {
unlink(imagePath, function (error) {
if (error) {
throw error;
}
// if no error is thrown, file has been deleted successfully
logger.info("File was deleted as it already exists in the db!");
});
};
This is the function for which I'm writing test case using vitest framework.
Though, I tried to write the test for it in the following way
deleteDuplicatedImage.spec.ts
require("dotenv").config();
import { nanoid } from "nanoid";
import { afterEach, describe, expect, it, vi } from "vitest";
import * as deleteDuplicatedImage from "../../src/lib/utilities/deleteDuplicatedImage";
const testImagePath: string = `${nanoid()}-testImagePath`;
describe("utilities -> deleteDuplicatedImage", () => {
afterEach(() => {
vi.restoreAllMocks();
});
it("it should throw an error", async () => {
const mockedDeleteDuplicatedImage = vi
.spyOn(deleteDuplicatedImage, "deleteDuplicatedImage")
.mockImplementation((_imagePath: any) => {});
deleteDuplicatedImage.deleteDuplicatedImage(testImagePath);
expect(mockedDeleteDuplicatedImage).toBeCalledWith(testImagePath);
expect(
deleteDuplicatedImage.deleteDuplicatedImage(testImagePath)
).toBeUndefined();
});
});
It is also passed but not including the coverage of the code!!
It should have 100% test coverage

Cypress is returning an empty array when trying to log sheetnames of an excel file

I am currently trying to get the sheetnames of an excel file but Cypress is returning an empty array. Is there something I missed? I'll be using it to verify data on later steps.
I'm using Cypress 9.6.0 with Cucumber. Below are my scripts and screenshots:
index.js for task
module.exports = (on, config) => {
on('file:preprocessor', cucumber());
on('task', {
checkExcelSheetContents(args){
if (fs.existsSync(args.filePath)) {
const workbook = xlsx.readFile(args.filePath);
return xlsx.utils.sheet_to_json(workbook.SheetNames)
} else {
throw new Error ("File not found")
}
}
})
return Object.assign({}, config, {
fixturesFolder: 'cypress/fixtures',
integrationFolder: 'cypress/integration',
screenshotsFolder: 'cypress/screenshots',
videosFolder: 'cypress/videos',
supportFile: 'cypress/support/index.js'
});
}
.js file
And ('try', () => {
var excelFilePath = "../CreateAutomatedTests/cypress/downloads/courses20220714_09_51_27.xlsx"
cy.wrap(excelFilePath).as('filePath')
cy.get('#filePath').then((filePath) => {
cy.task('checkExcelSheetContents', { filePath }).then((contents) => {
cy.log(contents)
})
})
})
Please see these screenshots as well
I've always used the buffer version of xlsx.read().
From xlsx package
For Node ESM, the readFile helper is not enabled. Instead, fs.readFileSync should be used to read the file data as a Buffer for use with XLSX.read:
import { readFileSync } from "fs";
import { read } from "xlsx/xlsx.mjs";
const buf = readFileSync("test.xlsx");
/* buf is a Buffer */
const workbook = read(buf);
Your task:
on('task', {
checkExcelSheetContents(args){
if (fs.existsSync(args.filePath)) {
const buf = fs.readFileSync(file);
const workbook = xlsx.read(buf, { type: 'buffer' });
return workbook.SheetNames
} else {
throw new Error ("File not found")
}
}
})

how to refer to a function when unit testing with NodeJS / Mocha

I'm making my first test with Mocha.
Dummy test is passing, but when I want to refer to my actual function that is in another file, it won't find it:
ReferenceError: main is not defined
I have a single index.js with :
async function main() {
function comparer(otherArray) {
return function (current) {
return otherArray.filter(function (other) {
return other.prm === current.prm && other.conso_prod === current.conso_prod
}).length === 0;
}
}
}
module.exports = main();
and in my test.js file, I do:
const {expect} = require('chai');
describe('Sum numbers', () => {
it('Compare 2 existing array', () => {
const meters = []
const perimeter = []
const onlyInMeters = meters.filter(main.comparer(perimeter));
expect(onlyInMeters).to.equal([]);
});
});
But when I refer to main.comparer, it can't find it:
ReferenceError: main is not defined
What am I forgetting? Sorry, I'm a NodeJS Noob!
It seems like you did not import the index.js file in test.js file. You are returning noting from main function as well.
Also, why are you exporting it like module.exports = main(); Instead you can do this:
// index.js
module.exports = {
comparer: (otherArray) => { ... }
}
// test.js
cosnt main = require('PATH_OF_index.js');
main.comparer();

webpack require expression missing modules

From webpack documentation, when a require expression is not known at compile time, it should generate a context module and include all the modules that could match the expression.
const handlers = {};
for (const name of Object.keys(SomeObject)) {
try {
handlers[name] = require(`./${name}.js`);
} catch {} // eslint-disable-line no-empty
}
module.exports = handlers;
however, what I get is `
const handlers = {};
for (const name of Object.keys(SomeObject)) {
try {
handlers[name] = require(`./${name}.js`);
} catch {} // eslint-disable-line no-empty
}
module.exports = handlers;
however, what I actually get is this error Cannot find module ./\u001a.js
but if I turn it into a dynamic import expression then it works
const handlers = {};
for (const name of Object.keys(SomeObject)) {
try {
import(`./${name}.js`).then(m => { handler[name] = m; });
} catch {} // eslint-disable-line no-empty
}
module.exports = handlers;
But I would prefer not to do that since the offending code is from some node package

compile typescript in chatbot

I'm trying to create a chatbot I'm following a tutorial on youtube
https://www.youtube.com/watch?v=cYuWse7GB9E
However at the end of the tutorial you build the typescript using the command Ctrl + Shift + b
my tsconfig.json file looks like this
{
"conpileOnSave":true,
"compileOptions":{
"module":"commonjs",
"target":"es6",
"sourceMap":true,
"declaration":false,
"removeComments":true,
"outDir":"./dist",
"allowJs":true
},
"files":[
"./lib/types.ts",
"./lib/app.ts"
]
}
and my app.ts file looks like this
import { BotFrameworkAdapter, MemoryStorage,ConversationState } from "botbuilder";
import * as restify from "restify";
//import { ConfState } from "./types";
let server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, () => {
console.log(`${server.name} listening on ${server.url}`);
})
const adaptor = new BotFrameworkAdapter({
appId: process.env.MICROSOFT_APP_ID,
appPassword: process.env.MICROSOFT_APP_PASSWORD
});
let conversationState;
const memoryStorage = new MemoryStorage();
conversationState = new ConversationState(memoryStorage);
//const conversationState = new ConversationState(new MemoryStorage());
adaptor.use(conversationState);
server.post("/api/messages",(req,res) => {
adaptor.processActivity(req,res,async(context) =>{
if(context.activity.type === "message") {
const state = conversationState.get(context);
await context.sendActivity(`you said ${context.activity.text}`);
} else {
await context.sendActivity(`${context.activity.type} event detected`);
}
})
});
my problem is that it builds, well doesn't have any errors but nothing is ever built into the "dist" folder so when I then run "node server.js" which contains this code
module.exports = require("./dist/app");
It throws an error
internal/modules/cjs/loader.js:638
throw err;
^
Error: Cannot find module './dist/app'
Has anyone any idea what is wrong. I have changed the permissions on the dist folder to full but still nothing.
thanks
my complete source code can be found here
https://github.com/andrewslaughter/chatbot/tree/master/video2

Resources