Generally, tests should not call any external services like Telegram or Discourse. The calls to their APIs should be mocked with smth like GitHub - nock/nock: HTTP server mocking and expectations library for Node.js
I can try to mock telegram api, but what about arcanist suspended on those tests, when I only test welcome page and form
describe("Endpoints test", () => {
const app = express();
let server: Server<typeof IncomingMessage, typeof ServerResponse>;
before(() => {
server = app.listen(3000, () => {
console.log("Server is listening on port 3000");
});
app.use(express.json());
app.use(router);
});
it("request to home page should has status 200", async () => {
await request(app).get("/").expect(200);
});
it("should return a html form for GET request to /authorize", async () => {
await request(app)
.get("/authorize")
.expect("Content-Type", /html/)
.expect(200);
});
after((done) => {
server.close();
done();
});
});
in this test, you import the main.ts
file, which in chained consequence imports also the bot.ts
file, which immediately tries to create a telegram bot instance - on import time. It might be beneficial to instead wrap the telegram bot logic into a function and only call it when it’s necessary. You can do a sort-of singleton with smth like
let bot:Bot | null = null
function makeBot(){
return new Bot(...)
}
export function getBot(){
if(!bot){
bot = makeBot()
}
return bot;
}
(the details are of course missing from this example, but it should get my point across)
@xanderazuaje you commented “db.run throws an exception when something went wrong with the request, thus, the subsequent checks could be avoided by modifying the properties when the table is created, for instance, making the ‘telegramId’ as an unique value (or even a primary key) is something that makes sense to both avoid the duplicates of users and make the run() method to throw when it’s necessary and nothing else.”
telegramId
is unique value, username not, at least by default. shall we consider scenario when telegramId
duplication occurs? What can be done here, what is the suggestion?
await db.run("INSERT INTO users (userName, telegramId) VALUES (?, ?)", [
userName,
telegramId,
]);
I’d set telegramId
as a key in db initialization
export const initDb = async () => {
try {
const db = await AsyncDatabase.open("users.db");
if (db) {
await db.run(
"CREATE TABLE IF NOT EXISTS users (telegramId PRIMARY KEY userName TEXT)"
);
}
return db;
} catch (err) {
console.error("Error when running db:", (err as Error).message);
}
};
As telegramId
is an unique value, in the table creation query setting it as a primary key, as you did, do the job of assuring that. If some user try to insert another register with a duplicated telegramID the db.run()
automatically throws the exception and can be handled