Lecture #13. ExpressJS. Web app testing
Lecture #13. ExpressJS. Web app testing
Лабораторна робота №1
Лабораторна робота №2
Лабораторна робота №3
2
Node.js Process Model
Traditional Web Server Model
In the traditional web server model, each request is handled by a dedicated
thread from the thread pool. If no thread is available in the thread pool at
any point of time then the request waits till the next available thread.
Dedicated thread executes a particular request and does not return to thread pool
until it completes the execution and returns a response.
Node.js Process Model
Node.js runs in a single process and the application code runs in a single
thread and thereby needs less resources than other platforms. All the user
requests to your web application will be handled by a single thread and all the
I/O work or long running job is performed asynchronously for a particular
request. So, this single thread doesn't have to wait for the request to
complete and is free to handle the next request. When asynchronous I/O work
completes then it processes the request further and sends the response.
3
Event Loop Example
const foo = () => console.log("First");
Source
const bar = () => setTimeout(() => console.log("Second"), 500);
const baz = () => console.log("Third");
bar();
foo();
baz();
4
Node.js Core Modules
http http module includes classes, methods and events to create Node.js
http server.
url url module includes methods for URL resolution and parsing.
querystring querystring module includes methods to deal with query
string.
path path module includes methods to deal with file paths.
fs fs module includes classes, methods, and events to work with file I/O.
util util module includes utility functions useful for programmers.
5
Load and Use Core http Module
var http = require('http');
var server = http.createServer(function(req, res){
//write code here
});
server.listen(5000);
In the above example, require() function returns an object because http module
returns its functionality as an object, you can then use its properties and methods
using dot notation e.g. http.createServer().
6
Writing Simple Module
In Node.js, module should be placed in a separate JavaScript file. So, create a
Log.js file and write the following code in it.
var log = {
info: function (info) {
console.log('Info: ' + info);
},
warning:function (warning) {
console.log('Warning: ' + warning);
},
error:function (error) {
console.log('Error: ' + error); var myLogModule = require('./Log.js');
} myLogModule.info('Node.js started');
};
C:\> node app.js
module.exports = log Info: Node.js started
7
NPM - Node Package Manager
Node Package Manager (NPM) is a command line tool that installs, updates or
uninstalls Node.js packages in your application. It is also an online repository for
open-source Node.js packages. The node community around the world creates
useful modules and publishes them as packages in this repository.
Install Package Locally
C:\>npm install <package name> Uninstall Packages
Add Dependency into package.json C:\MyNodeProj> npm uninstall
C:\MyNodeProj> npm install express --save express
Install Package Globally
C:\MyNodeProj> npm install -g express
8
package.json
A package.json file, usually present in the project root, contains metadata about
your app or module as well as the list of dependencies to install from npm when
running npm install.
To initialize a package.json type npm init in your command prompt.
9
properties of package.json
"scripts": {
"test": "vows --spec --isolate",
"start": "node index.js",
{ "predeploy": "echo About to deploy",
"name": "module-name", "postdeploy": "echo Deployed",
"version": "10.3.1", "prepublish": "coffee --bare --compile --output
"description": "An example module", lib/foo src/foo/*.coffee"
"author": "Your Name },
<[email protected]>", "main": "lib/foo.js",
"contributors": [{ "dependencies": {
"name": "Foo Bar", "express": "4.2.x"
"email": "[email protected]" },
}], "devDependencies": {
"bin": { "assume": "<1.0.0 || >=2.3.1 <2.4.5 || >=2.5.2
"module-name": "./bin/module-name" <3.0.0"
}, },
"files": [
"lib/foo.js"
] 10
Create Node.js Web Server
Node.js makes it easy to create a simple web server that processes incoming
requests asynchronously.
The following example is a simple Node.js web server contained in server.js file.
server.js
var http = require('http'); // 1 - Import Node.js core module
var server = http.createServer(function (req, res) { // 2 -
creating server
//handle incomming requests here..
});
server.listen(5000); //3 - listen for any incoming requests
13
Advantages of Express.js
● Makes Node.js web application development fast and easy.
● Easy to configure and customize.
● Allows you to define routes of your application based on HTTP methods and
URLs.
● Includes various middleware modules which you can use to perform
additional tasks on request and response.
● Easy to integrate with different template engines like Jade, Vash, EJS etc.
● Allows you to define an error handling middleware.
● Easy to serve static files and resources of your application.
● Allows you to create REST API server.
● Easy to connect with databases such as MongoDB, Redis, MySQL
14
Express.js Web Application
15
Configure Routes in Express.js
var express = require('express');
var app = express();
16
Serve Static Resources using
Express.js
server.js Copy
var express = require('express');
var app = express();
//setting middleware
app.use(express.static(__dirname + 'public')); //Serves resources from public
folder
var server = app.listen(5000);
17
Data Access in Node.js
Relational
Databases Driver NPM Command
18
SQLite Node.js
const sqlite3 = require('sqlite3').verbose();
app.listen(5000); 21
Example: Ajax, NodeJS, Express
home.html
<html lang="en">
<head>
<title>Example</title>
</head>
<body>
<p id='data'>Data is loading... </p>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
async function getData() {
let p = document.querySelector('#data');
var result = await axios('/get-data/');
var timeout = await new Promise(() => setTimeout(() => {
p.innerHTML = result.data['message']}, 3000));
}
getData();
</script>
</body>
22
</html>
Example: Ajax, NodeJS, Express
(refreshing every second)
<html lang="en">
<head>
<title>Example</title>
</head>
<body>
<p id='data'>Data is loading... </p>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
function getData() {
let p = document.querySelector('#data');
setInterval(async ()=>{
var result = await axios('/get-data/');
p.innerHTML = result.data['message'];
}, 1000);
}
getData();
</script> 23
Registration & Authentication
24
Web UI Testing importance
Web UI testing is crucial for ensuring that web applications function
correctly, meet user requirements, and provide a positive user
experience. Here's why it's important and some ways to conduct it
effectively:
User Experience (UX) Assurance: The UI is what users interact with
directly. Testing ensures that the interface is intuitive, responsive, and
aesthetically pleasing.
Functional Validation: UI testing verifies that all elements on the page
function as expected. This includes buttons, links, forms, menus, etc.
Cross-browser and Cross-device Compatibility: Ensuring that your UI
works consistently across different browsers and devices is essential for
reaching a broad audience.
Accessibility Compliance: Testing ensures that the UI is accessible to
users with disabilities, meeting relevant standards such as WCAG (Web
Content Accessibility Guidelines).
Brand Image and Credibility: A well-designed and error-free UI reflects
positively on the brand and instills confidence in users. 25
Ways to Conduct Web UI Testing
Manual Testing:
Exploratory Testing: Manual exploration of the application to uncover UI issues,
usability problems, and inconsistencies.
Usability Testing: Involves real users to evaluate the UI's ease of use, efficiency,
and overall user satisfaction.
Automated Testing:
Functional Testing: Automated tests to verify that UI elements function correctly.
Tools like Selenium, Cypress, or Puppeteer can be used.
Visual Testing: Tools like Applitools or Percy capture screenshots of UI
components and compare them to baseline images to detect visual regressions.
Cross-browser Testing: Tools like BrowserStack or Sauce Labs automate testing
across various browsers and devices.
Accessibility Testing: Tools like Axe or Pa11y can be used to automatically test
for accessibility issues.
26
Ways to Conduct Web UI Testing
(2)
Responsive Design Testing:
Ensures that the UI adapts and displays correctly across different screen sizes.
Tools like Browser's developer tools or Responsinator can assist in this.
Performance Testing:
Evaluates how quickly the UI responds and loads under different conditions. Tools
like Lighthouse or GTmetrix can be used for performance analysis.
Regression Testing:
Regularly test the UI to ensure that new features or changes haven't introduced
any unintended side effects.
Security Testing:
While not purely UI testing, it's important to ensure that the UI doesn't expose
security vulnerabilities such as XSS (Cross-Site Scripting) or CSRF (Cross-Site 27
Best practices
Early Testing: Start testing early in the development process to catch issues
sooner.
Test Coverage: Ensure that UI testing covers all critical paths and user
interactions.
Test Data: Use realistic data sets for testing to mimic real-world scenarios.
Regular Updates: Keep tests updated as the UI evolves.
Collaboration: Encourage collaboration between developers, designers, and
testers to ensure a comprehensive approach to UI testing.
Documentation: Document UI testing procedures, results, and issues for future
reference and improvement.
28
UI Testing
Acceptance tests are formal tests executed to verify if a system satisfies its
business requirements. They require the entire application to be up and
running and focus on replicating user behaviors. But they can also go further
and measure the performance of the system and reject changes if certain goals
are not met.
Differences between Acceptance
and E2E Testing
1. Purpose / Goal
Acceptance Tests check if the system satisfies business or customer requirements.
E2E Tests check if all parts of the system work together technically.
2. Perspective
Acceptance Testing is from the business or user perspective (e.g., "Can a user buy a product?").
E2E Testing is from the technical user flow perspective (e.g., "Does the 'Buy' button work end-
to-end?")
3. Ownership
Acceptance Tests are often defined by Product Owners, Business Analysts, or QA, possibly
involving non-technical stakeholders.
E2E Tests are usually written by developers or QA engineers using automated tools.
4. Automation: Acceptance tests may be manual or automated. E2E tests are mostly
automated.
36
5. Timing: Acceptance often happens near release ("final check before delivery"). E2E tests run