Creating a “hello world” with Express and typescript

Crear un "Hello World" con Express y typescript le da el primer paso con estas dos tecnologías utilizadas en el desarrollo web

Creating a hello world with typescript and express If you’re new to the world of web development, chances are you’ve heard of typescript and Express.js. Typescript is a superset typed JavaScript that brings more security and scalability to JavaScript code, while Express.js is a popular framework for building web applications and APIs with Node.js. In this tutorial, we will create a simple “Hello World” using these two technologies. Pre requirements Before we get started, make sure you have Node.js and npm installed on your system. You can download and install the latest version of Node.js from nodejs.org. Step 1: Configuring the development environment First, let’s create a new directory for our project and navigate to it: mkdir hello-world cd hello-world Then, initialize a new Node.js project by running the following command: npm init -y This command creates a ‘package.json’ file with the default settings for your project. Step 2: Installing the dependencies Now, we need to install the necessary dependencies for our project, including Express.js and typescript. Run the following command to install these dependencies: npm install express typescript @types/express Express.js: This is the framework we will use to handle HTTP routes and requests. Typescript: It is the language we will use to write our code. @types/express: These are the type definitions for Express.js, allowing us to write Express-compatible typescript code. Step 3: Configuring typescript Let’s create a configuration file for typescript called ‘tsconfig.json’. This file contains the configuration options for the typescript compiler. Run the following command to create this file: npx tsc –init Then open the file ‘tsconfig.json’ and make the following changes: { "compilerOptions": { "target": "es6", "module": "commonjs", "outDir": "./dist", "rootDir": "./src", "strict": true } } These options configure typescript to compile our code to the ‘dist’ directory and enable strict type checks. Step 4: Writing the code Now it’s time to write our code. Create a file called index.ts at the root of your project and add the following code: import express from 'express'; const app = express(); const port = 3000; app.get('/', (req, res) => { res.send('Hello, World!'); }); app.listen(port, () => { console.log(`Server is running at http://localhost:${port}`); }); This code creates an Express server that listens on port 3000 and responds with “Hello World!” when we access the root route (‘/’). Step 5: Compiling and running the code Now that our code is written, we need to compile it to JavaScript and run it. Run the following command to compile the typescript code: npx tsc This will compile the typescript code into JavaScript and place it in the dist directory. Finally, execute or follow the command to start or server: node dist/index.js You can now open your browser and go to ‘http://localhost:3000’ to see the “Hello World!” being displayed. Conclusion In this tutorial, you learned how to create a simple “Hello World” using typescript and Express.js. You set up the development environment, installed the required dependencies, configured the typescript, wrote the code, and ran the server. This is just the beginning, and you can expand this project by adding more functionality as you learn about APIs.

How to Implement Automated Tests with Cypress

Posted On: 2 fevereiro 2024 Posted by: Cercal Introduction The importance of testing is fundamental to ensure the quality, reliability, and performance of software. Some of the positive aspects that highlight the relevance of testing in web environments include: Bug detection: Testing allows for the identification of issues in the code, helping to correct them before they reach the production environment, saving time and resources. Ensure compliance with requirements: Testing ensures that the application meets the functional and non-functional requirements defined at the beginning of the development. Improve stability: Regular testing contributes to the software’s stability, reducing the likelihood of failures and unexpected crashes during use. Facilitates maintenance: Automated tests simplify the maintenance process, enabling the quick detection of regressions when new features are added or changes are made. In summary, testing plays a crucial role in the software development life cycle, contributing to the construction of robust, reliable applications capable of meeting user expectations. The Cypress Cypress stands out as a robust and efficient tool for end-to-end test automation, providing a modern and user-friendly approach to ensuring the quality of web applications. Simplicity and clarity: Cypress is known for its simple and clear syntax, making test writing accessible even for those with limited experience in automation. Browser Execution: One of Cypress’ features is the ability to run tests directly in the browser. This provides real-time visibility into the application’s behavior, allowing for quicker and more effective debugging. Real-time Visualization: During test execution, Cypress provides a real-time visualization, allowing developers to observe the tested application step by step. Isolated Environment: Each test in Cypress runs in an isolated environment, ensuring consistency and independence between tests. This contributes to the reliability and reproducibility of test results. Cypress emerges as a comprehensive tool for end-to-end test automation, combining simplicity, speed, and real-time visibility. Its modern approach and distinctive features make it a powerful choice for development teams committed to quality and efficiency in their web applications. Cypress Installation Installing Cypress in a project is relatively simple. Steps to start a project from scratch with Cypress: Start a Node.js project: make sure your Node.js project is up and running. Otherwise, run the following command in the command line to initialize a new Node.js project. npm init -y Install Cypress as a development dependency: Run the following command in the terminal within your project folder to install Cypress as a development dependency: npm i –save-dev cypress Open Cypress for the first time: After the installation is complete, run the following command to open Cypress for the first time. This will create the initial Cypress project structure, including the “cypress” folder and some example files. npx cypress open Configure script in package.json (optional): To simplify the use of Cypress, add scripts to the package.json file. For example: "scripts": { "test": "cypress run", "test:open": "cypress open" } Writing tests with Cypress To start, let’s create a simple HTML form. Create the index.html file in the project’s root folder with the following content: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Example Page</title> </head> <body> <h1>Cypress Test – Example Page</h1> <label for="name">Name:</label> <input type="text" id="name" name="name"> <label for="email">Email:</label> <input type="email" id="email" name="email"> <button id="btn-send">Send</button> <button id="btn-reset">Reset</button> <p id="result"></p> <script> document.getElementById('btn-send').addEventListener('click', function() { var name = document.getElementById('name').value; var email = document.getElementById('email').value; document.getElementById('result').innerHTML = 'Sent: ' + name + ', ' + email; }); document.getElementById('btn-reset').addEventListener('click', function() { document.getElementById('name').value = ''; document.getElementById('email').value = ''; document.getElementById('result').innerHTML = ''; }); </script> </body> </html> Create the file `myfirsttest.cy.js` in `cypress/e2e/1-getting-started/` with the following content: describe("Tests on the Example Page", () => { beforeEach(() => { cy.visit("index.html"); }); it("Should fill in fields and click Send", () => { cy.get("#name").type("John Doe"); cy.get("#email").type("[email protected]"); cy.get("#btn-send").click(); cy.get("#result").should( "have.text", "Sent: John Doe, [email protected]" ); }); it("Should reset fields when clicking Reset", () => { cy.get("#name").type("John Doe"); cy.get("#email").type("[email protected]"); cy.get("#btn-reset").click(); cy.get("#name").should("have.value", ""); cy.get("#email").should("have.value", ""); cy.get("#result").should("not.be.visible"); }); }); Test 1: Should fill in fields and click Send This test checks if the ‘Name’ and ‘Email’ fields can be filled, and if the ‘Send’ button performs the expected action. it('Should fill in fields and click Send', () => { // Fill in the Name and Email fields cy.get('#name').type('John Doe'); cy.get('#email').type('[email protected]'); // Click the Send button cy.get('#btn-send').click(); // Verify if the result is displayed correctly cy.get('#result').should('have.text', 'Sent: John Doe, [email protected]'); }); Test 2: Should reset fields when clicking Reset This test checks if the ‘Name’ and ‘Email’ fields are reset correctly when the ‘Reset’ button is clicked. it("Should reset fields when clicking Reset", () => { // Fill in the Name and Email fields cy.get('#name').type('John Doe'); cy.get('#email').type('[email protected]'); // Click the Reset button cy.get('#btn-reset').click(); // Wait for a short period to ensure the previous action is completed cy.wait(500); // Verify if the fields have been reset cy.get('#name').should('have.value', ''); cy.get('#email').should('have.value', ''); // Verify if the result is no longer visible cy.get('#result').should('not.be.visible'); }); Resultado https://website.mmti.io/wp-content/uploads/2024/01/myfirsttest.cy_.js.mp4 These tests are designed to ensure that user interaction with the fields and buttons on the page works as expected. They also demonstrate Cypress’s ability to handle these interactions effectively. Conclusion Effective implementation and execution of tests are crucial aspects of software development, and Cypress stands out as a powerful tool for end-to-end test automation in web applications. In this tutorial, we explored the installation of Cypress in a project, wrote basic tests, and highlighted some of the key features of the tool. When writing tests with Cypress, we observed the simplicity and clarity of its syntax, making it easy to create and maintain test cases. We explored fundamental commands like cy.get(), cy.click(), and cy.type(), which enable intuitive interactions with page elements. Practical examples of tests covered common scenarios, including navigation, interaction with elements, and result verification. We demonstrated how to create a robust testing environment, from opening a page to checking specific results. Despite the initial challenge of verifying the non-existence of the #result element, we adjusted the approach to handle it, ensuring that the tests are more robust and reliable. In summary, Cypress offers a modern approach to end-to-end test automation, providing simplicity,

Deciphering TypeScript: A Journey through the Nooks of the Language that Transforms JavaScript

Introduction With the increasing complexity of modern web applications, there is a need for more powerful tools for developers. In this context, TypeScript stands out as an extension of JavaScript that offers static types, making maintenance and error detection easier even before the code execution. Let’s explore the reasons why TypeScript has been rapidly gaining popularity and how it can significantly improve the development experience. What is the TypeScript? TypeScript is an open-source programming language developed by Microsoft. It’s an extension of JavaScript that adds static typing features to the code. In other words, TypeScript allows developers to specify the data type of variables, function parameters, and return values, which helps detect programming errors during development. Why use it? In large projects, TypeScript facilitates code maintenance by providing clear information about the types of data used. This makes the code more understandable, facilitates collaboration among developers, and reduces the risk of introducing errors during changes. Additionally, as mentioned in the introduction, TypeScript is compatible with the JavaScript ecosystem, which means you can easily integrate TypeScript code into existing JavaScript projects. Furthermore, with static types, refactorings can be performed more safely, especially in large projects where changes can have complex side effects. Main features of TypeScript TypeScript has several native features, here are some of them: Static Typing: TypeScript allows the definition of types for variables, function parameters, object properties, etc. This helps detect type errors during development, providing an additional layer of security. Type Inference: Even if you don’t explicitly specify types, TypeScript can infer types based on the context of the code. This reduces the need for verbose type declarations. Interfaces: TypeScript supports the creation of interfaces, which can be used to define contracts for objects. This is useful for ensuring that objects have the necessary properties. Enums: Enums allow the creation of named sets of constant values, which can make the code more readable and maintainable. Union Types and Intersection Types: TypeScript offers the ability to combine types using union (|) and intersection (&) types, allowing greater flexibility in data modeling. Generics: Generics allow you to create components and functions that can work with a variety of types, providing code reuse and greater flexibility. Namespaces and Modules: TypeScript supports code organization using namespaces and modules, helping to avoid naming conflicts and improve project structure. Decorators: Decorators are a way to add metadata to classes and members, allowing for extensibility and additional features, such as those used in frameworks like Angular. Mixins: TypeScript supports mixins, a technique for sharing functionality between classes in a flexible way. Strict Null Checks: When enabled, this option enforces null and undefined checks, helping to avoid many common errors in JavaScript. TypeScript Compiler (tsc): TypeScript has its own compiler (tsc) that converts TypeScript code into JavaScript, making it easy to integrate with existing projects. ES6/ESNext Support: TypeScript has support for the latest ECMAScript features, allowing the use of advanced JavaScript features. Integration with Development Tools: TypeScript is well integrated with various tools, such as code editors (VSCode, Atom, etc.) and build systems (Webpack, etc.). JavaScript Compatibility: TypeScript is backward compatible with JavaScript, meaning you can gradually add TypeScript to existing projects without the need for a complete rewrite. How is the syntax? The syntax of TypeScript is quite simple, just like JavaScript’s. I’ve developed a simple calculator to show you exactly how the syntax isn’t difficult. class Calculator { add(a: number, b: number): number { return a + b; } subtract(a: number, b: number): number { return a – b; } multiply(a: number, b: number): number { return a * b; } divide(a: number, b: number): number { if (b === 0) { throw new Error("Cannot divide by zero"); } return a / b; } } const calculator = new Calculator(); const sum = calculator.add(5, 3); console.log("Soma: ", sum); const difference = calculator.subtract(8, 4); console.log("Subtração: ", difference); const product = calculator.multiply(2, 6); console.log("Multiplicação: ", product); try { const quotient = calculator.divide(10, 2); console.log("Divisão: ", quotient); } catch (error: any) { console.error(error.message); } The syntax, as you can see, is simple. The biggest difference indeed is the typing, which more experienced programmers have already noticed. But if you don’t know much about programming, don’t worry. I’ll explain to you where these typings are. Notice that in the function parameters, inside the ‘Calculator’ class, we have: a: number, b: number This means that this function takes numbers as parameters. If when this function is called, there’s a string in the parameters, TypeScript itself recognizes it as an error and alerts you, not even allowing the code to be executed. How to run the code To run a TypeScript code, we need to compile it into JavaScript first. Although sometimes the name ‘compile’ may seem a bit intimidating, the process is quite simple. In your terminal, in the project folder, run the command tsc –init This will start the tsconfig, the TypeScript configuration file, which will take care of compiling our code. Now let’s compile the code itself by running the command tsc -w Note that now a ‘.js’ file has been created in your project folder, and it’s this file that we’ll actually run. Finally, let’s run what we’ve done. To do this is simple, but first, make sure you have NodeJS installed on your machine with the command node -v If you don’t have it, go to https://nodejs.org/en After Node is properly installed, you’re 100% ready to run the project. Just run (without ‘<‘ and ‘>’) node <meu-projeto>.js There you go, now you’ve run your first TypeScript project, and you’ve got a better understanding of what TypeScript is all about.