Category: Client-Side Security

Jscrambler joins PCI SSC Brazil Advisory Board

The PCI Security Standards Council (PCI SSC) announced a new roster of 35 payments leaders to serve on its 2024-2025 Brazil Regional Engagement Board. Carlos Rocha Gonçalves, VP of Growth, and Gustavo Marques, Product Manager, represent Jscrambler on the Brazil Regional Engagement Board.

In this role, Jscrambler will represent the perspectives of PCI SSC Participating Organizations and PCI SSC constituents in Brazil, advising and providing feedback and guidance to the PCI SSC on standards and program development and adoption in Brazil.

Jscrambler – PCI SSC Advisory: board responsibilities

Board members act as advisors to the Council on payment security issues and challenges in the region and as ambassadors for helping increase education and awareness of standards and best practices for securing payment data. 

“The Regional Engagement Board creates a synergy of regional stakeholders from different sectors of the payment industry in Brazil working together to support the security of payment data,” said Guilherme Scheibe, PCI SSC Regional Director, Latin America and Caribbean. “Collaborating with Jscrambler and fellow Board members is crucial in fortifying the foundation of secure payments for the future.” 

The Board will meet regularly throughout the year to discuss payment data security issues, trends, and market changes. Its key priorities in 2024-2025 include:

  • Awareness of PCI DSS v4.0: enhance understanding of PCI DSS v4.0 requirements and processes, facilitating the transition to the latest PCI Security Standard version.

  • Educational resources: expand collaboration for the development of content and resources within the payment industry in the region.

  • Strategic market understanding: identify current and future market trends.

  • Awareness of key security initiatives: drive regional awareness and understanding of PCI Standards and initiatives.

  • Training: foster greater awareness and understanding of payment security through PCI Training initiatives.

  • Translations: identify translation needs and priorities to enhance effective communication with the regional stakeholders.

  • Participation: facilitate the growth of Participating Organizations in Brazil and throughout the region through active engagement and support. 

“The expanded PCI SSC Brazil Regional Engagement Board gives us even greater insight into the payment data security issues, trends, and market changes in the region,” says Gina Gobeyn, Executive Director of PCI SSC. “Improving and increasing industry involvement – in Brazil and around the world – in the development of PCI Standards and resources is critical to the Council’s mission to enhance global payment security.” 

About PCI Security Standards Council

The PCI Security Standards Council (PCI SSC) leads a global, cross-industry effort to increase payment security by providing industry-driven, flexible, and effective data security standards and programs that help businesses detect, mitigate, and prevent cyberattacks and breaches. 

Europol Identifies 400 Online Merchants as Victims of E-Skimming

More than 400 online merchants were found to be infected with e-skimmers following a coordinated international action by law enforcement.

The two-month campaign by Europol and law enforcement agencies in 17 countries identified infected e-commerce sites and alerted them that their customers’ card data had been compromised.

It resulted in two dozen new e-skimmers, i.e. malicious software or ‘malware’ types, being identified. These include AngryBeaver, ATMZOW, FirstKiss, FakeGA, health_check, Inter and R3nin.

What is E-skimming?

E-skimming, or digital skimming, involves stealing sensitive data inputted by users into web forms. Frequently this is payment data from online checkout pages, although it also includes personally identifiable information, or PII for short, from other web forms.

E-skimming goes by many names, including digital skimming, data skimming, and formjacking. Then there are the more specific terms of JavaScript attacks or Magecart attacks, which hint at how skimming works.

Criminals exploit vulnerabilities in a website’s code or infrastructure to harvest data. These attacks are hard to detect as the payment process is unaffected. The customer gets their goods or services and the merchant gets paid. Both parties are unaware that a compromise may have occurred.


LEARN MORE How to Strengthen E-commerce Security Against E-skimming Threats


How Does E-skimming Work?

In general, there are four stages in an e-skimming attack:


1. Initial breach

Criminals gain access to the source code of the server of an online store either as a first-party attack or by compromising a third party. Often this is by exploiting software vulnerabilities, deploying malware, or using stolen (or phished) credentials.

2. Code injection

Criminals inject malicious code to compromise payment pages. They evolve their methods. And tailor them depending on whether payment forms appear directly on pages or are embedded using an iFrame.

JavaScript attacks, as the name suggests, target the programming language used by more than 98% of websites to create interactive pages. 

Magecart attacks are named after ‘Magento’, the primary open-source e-commerce platform, and shopping ‘cart’. Magecart also refers to the criminal group active since 2015 carrying out such attacks.


3. Data exfiltration

The harvesting of data occurs when consumers enter their payment details to complete their purchases on compromised payment pages. The malicious code covertly skims and collects the information, often encrypting it, before sending it to the attacker’s remote server.

4. Monetization

Criminals monetize stolen data by using it to make unauthorized, fraudulent purchases for goods to re-sell for cash. Or by selling the data to other criminals.

How Did We Get Here?

The Internet was designed for sharing and collaboration not necessarily banking and shopping. How web applications are built has also changed over time. 

The business intelligence has moved from web servers, owned and managed by companies, into the consumer web browser, powered by JavaScript, distributed APIs, and microservices.

As a result, any JavaScript running on a browser can access all data entered into form fields on that page. With no separation between different application parts, this makes payment pages susceptible to client-side attacks, such as skimming.

What’s the Solution?

Don’t underestimate the importance and effectiveness of business-as-usual security. There are various steps e-commerce businesses can take to protect themselves from e-skimming attacks and prevent unauthorized access to sensitive data. 

These range from conducting regular security assessments, monitoring, and third-party due diligence to deploying secure code and adhering to payment security standards (PCI DSS).

The latter is becoming increasingly important as version 4.0 of the PCI DSS contains two new requirements to protect against and detect these e-skimming attacks on payment pages. These will be requirements from 01 April 2025.

The first requirement (6.4.3) is designed to minimize the attack surface and manage all JavaScript present on the payment page. The second requirement (11.6.1) aims to detect tampering or unauthorized changes to the payment page and generate an alert when changes are detected.

Jscrambler Client-Side Protection Platform

The Jscrambler Client-Side Protection Platform safeguards first-party JavaScript through state-of-the-art obfuscation and exclusive runtime protection.

Its fine-grained JavaScript behavioral analysis also mitigates threats and risks posed by third-party tags all while ensuring compliance with the new PCI DSS v4.0 standard. With Jscrambler, businesses adopt a unified, future-proof client-side security policy all while achieving compliance with emerging security standards.

Trusted by digital leaders from several industries, including financial, healthcare, and entertainment, Jscrambler gives businesses the freedom to innovate securely.

Feel free to connect with our client-side security experts to try our solutions to prevent digital skimming attacks.

Jscrambler Joins FS-ISAC in New Partnership in New Partnership

Jscrambler has joined FS-ISAC as an affiliate member. This decision signals its commitment to safeguarding financial services organizations from digital skimming, IP theft, and payment risks. This partnership will address the pressing need for advanced client-side protection and compliance within the global financial sector.

Mitigating JavaScript risk in financial services with client-side protection

As the financial services industry increasingly relies on JavaScript to enhance web experiences and functionality, first- and third-party JavaScript risk mitigation has become a top priority.

It’s not uncommon for financial organizations to have public-facing websites with over 50 third-party tags from Google, Facebook, LinkedIn, and Adobe with 10,000+ data access attempts unknown to application, information security, and compliance teams. 

Jscrambler has a proven track record working with global financial institutions to address these critical needs for proactive measures to secure applications that rely on JavaScript, safeguarding sensitive data while ensuring the uninterrupted delivery of financial services and consumer trust.

Jscrambler pioneered the concept of client-side protection for JavaScript, being the first company to provide comprehensive JavaScript obfuscation and third-party tag protection while helping organizations achieve PCI DSS v4 compliance.

Ten years into the journey, our track record of industry-first innovations and continuous advancements has firmly established Jscrambler as the unrivaled leader in the Client-Side Protection and Compliance Platform category. Jscrambler provides financial institutions unparalleled security, enabling them to fortify their JavaScript code against emerging threats.

As a new FS-ISAC partner, Jscrambler is offering all members a free trial of its industry-leading client-side protection and compliance Platform to assess five essential requirements:

  1. Comprehensive coverage of first-party code obfuscation and third-party vendor tag data control.

  2. Best-of-breed capabilities.

  3. Enforcement of a company-wide client-side protection policy.

  4. Top-notch performance.

  5. Trusted JavaScript expertise.

Looking Ahead with FS-ISAC


FS-ISAC is a non-profit, member-driven organization dedicated to enhancing cybersecurity and resilience in the worldwide financial system. Their mission is to safeguard financial institutions and the individuals served by them.

Their headquarters is based in the US, with offices in the UK and Singapore, with membership spanning approximately 70 countries.

Jscrambler: a member of the FS-ISAC affiliate program

Jscrambler is excited to actively participate in FS-ISAC working groups dedicated to addressing cybersecurity challenges in the financial industry.


As part of our commitment to ongoing collaboration and knowledge sharing, we are excited to engage with industry experts and stakeholders at the upcoming FS-ISAC’s 2024 Americas Spring Summit in San Diego, California, USA (March 3-6).

Together, we aim to stay ahead of evolving threats and reinforce the resilience of financial services against JavaScript-related risks.

Jscrambler Wins 2024 BIG Innovation Award for Second Consecutive Year

Porto, Portugal – January 10, 2024

Jscrambler, the pioneering platform for client-side protection, today announces it has been named a winner in the 2024 BIG Innovation Awards presented by the Business Intelligence Group for the second consecutive year. Jscrambler’s Client-Side Protection Platform has been recognized amongst global technology organizations whose innovative approach and platform have caused market disruption. 

Jscrambler was the first to merge advanced polymorphic JavaScript obfuscation with fine-grained third-party tag protection in a unified Client-Side Protection and Compliance Platform. Its integrated solution ensures a robust defense against current and emerging client-side cyber threats, data leaks, and IP theft, empowering software development and digital teams to innovate securely.

With Jscrambler, businesses adopt a unified, future-proof client-side security policy all while achieving compliance with emerging security standards including PCI DSS v4.

“Client-side protection is now a must-have for any modern digital business,” said Rui Ribeiro, CEO and Co-founder of Jscrambler. “The use of JavaScript to improve the overall web experience has become core to digital business operations, but the underlying scripts that power each page are often the target of cyber criminals performing e-skimming attacks on unknowing customers. Given JavaScript has expanded the surface area risk of every web page, we appreciate and thank BIG for their continued acknowledgment of our efforts to secure the client side of the web.”

“Innovation is driving our society,” said Maria Jimenez, chief nominations officer of the Business Intelligence Group. “We are thrilled to be honoring Jscrambler as they are leading by example and improving the lives of so many.”

Organizations from across the globe submitted their recent innovations for consideration in the BIG Innovation Awards. Nominations were then judged by a select group of business leaders and executives who volunteered their time and expertise to score submissions.

About Jscrambler client-side protection solution


Jscrambler is the leader in Client-Side Protection and Compliance. Jscrambler is the first to merge advanced polymorphic JavaScript obfuscation with fine-grained third-party tag protection in a unified Client-Side Protection and Compliance Platform.

Jscrambler’s integrated solution ensures a robust defense against current and emerging client-side cyber threats, data leaks, misconfigurations, and IP theft, empowering software development and digital teams to innovate securely.

Code Integrity

Jscrambler’s Code Integrity product safeguards first-party JavaScript through state-of-the-art obfuscation and exclusive runtime protection. 

Webpage Integrity

Jscrambler’s Webpage Integrity product mitigates threats and risks posed by third-party tags all while ensuring compliance with the new PCI DSS v4.0 standard. With Jscrambler, businesses adopt a unified, future-proof client-side security policy all while achieving compliance with emerging security standards. 

Jscrambler’s customers include FORTUNE 500, e-comm, airlines, media, and financial services companies whose success depends on safely engaging with their customers online. 

About Business Intelligence Group


The Business Intelligence Group was founded with the mission of recognizing true talent and superior performance in the business world. Unlike other industry award programs, these programs are judged by business executives who have experience and knowledge.

The organization’s proprietary and unique scoring system selectively measures performance across multiple business domains and then rewards those companies whose achievements stand above those of their peers.

Future perfect: Jscrambler’s client-side protection and AI

AI cybersecurity is so hot right now. The corporate upheavals at OpenAI – the firm behind the ChatGPT chatbot – have given artificial intelligence an even higher profile over recent days but AI technology plays a prominent role in everything from mapping apps to corporate web development.

AI cybersecurity: JavaScript ex-machina


AI complements the work of human programmers by making the development process more efficient through the use of coding assistants.

JavaScript has moved from a tool for internal developers into a technology that allows businesses to improve their ability to operate and innovate on the web. 

Visibility and control over how tools and AI platforms collect data are becoming increasingly important even before we consider how evolving AI technology might be abused to develop client-side attacks.

Threat actors can harness AI tools, in particular LLM (large language model) tools such as ChatGPT and Google Bard, to improve the ability to attack internal code. For example, hackers can exploit debuggers or try to tamper with code using AI-based tools.

[LEARN MORE] Anti-debugging technique

AI tools have also increased the ability of script vendors to collect more data. This creates a raft of data leakage and data privacy issues.

Novel attack vectors

Deployment of artificial intelligence can increase the attack surface of software systems whilst also setting up the possibility of more advanced client-side attack vectors.

For example, Israeli security start-up Adversa has shown how machine learning systems might be vulnerable to so-called adversarial attacks. Datasets used to train machine learning systems might be poisoned with maliciously crafted data samples, Adversa warns.

Changing the script

JavaScript plays a significant role in the integration of AI into web development. With the growing availability of machine learning libraries, JavaScript developers can now integrate machine learning and artificial intelligence into web application development through technologies such as TensorFlow.js.

Continuous updates have increased the attack surface of JavaScript, a trend that AI is reinforcing and accelerating. Modern web applications load an average of 20+ third-party scripts, creating a software supply chain risk.

Potential vulnerabilities include broken access controls, data leakage, formjacking, account takeovers, and more.

Commercial imperatives are driving the use of Javascript to support business goals, for example by allowing organizations to hyper-personalize the user experience using data from affiliate websites.

For example, e-commerce operations are using tags and scripts to gather information needed to personalize the user experience.

Advertising tags, pixel social media tags, marketing tags – chatbot, a/b testing, analytics, payment tags, performance tags, and more are all giving the business the data needed to improve the customer web experience.

AI-powered tags are collecting more and more data at an accelerating rate through mechanisms the “business” has no visibility upon and little ability to control – hence the need for businesses to rethink their security strategy.

Client-side protection

JavaScript is where the rubber hits the road in the arena of web development. Both corporate intellectual property and end users need to be protected from malicious activity delivered through the medium of dynamic web pages.

A growing number of organizations are recognizing that protecting the client side of their web apps is needed to stay compliant with standards like PCI DSS v4, and better shield their c personal data, while also serving to improve web security maturity more generally.

Businesses need a holistic security solution that can deliver a combination of advanced first-party JavaScript obfuscation and state-of-the-art third-party script protection.

Client-side risks visualized

Jscrambler offers a comprehensive client-side protection and compliance platform that includes obfuscation and runtime protection tools for safeguarding a first-party code and a solution for effectively monitoring third parties in real-time, as well as blocking their access to sensitive data.

By using Jscrambler’s platform, clients gain real-time visualization of any script that could represent a threat to the integrity of the user’s data, highlighting behaviors understood as undesirable or suspicious.

Jscrambler ‘s platform can, amongst other functions, catalog all vendors and cross-reference this data with the rules that can be configured to develop a compliance policy. The software provides detection of a wide variety of attacks:

  •  Detecting web-based supply chain attacks.

  •  Detecting data exfiltration (e.g. Magecart).

  •  Avoiding poisoning and tampering with the DOM.

  •  Protecting against web-based threats and malware.

  •  Reporting threats detected in near real-time to the backend of the applications, allowing a quick reaction to address the threat.

  • Gaining visibility of any client-side changes.

This collective functionality helps organizations to ensure the integrity of payment pages – a key new requirement of the revised PCI DSS v4 payment industry regulations due to become mandatory at the end of March 2025.

Magecart

Over recent years, an array of cybercrime groups have attempted to inject web credit card skimmers on e-commerce and payment websites through so-called Magecart-style attacks.

British Airways, the most high-profile victim to date, from a Magecart-style attack, was fined £20m ($25.4m) for a data breach that affected more than 400,000 customers by the UK’s Information Commissioner’s Office.

In the summer of 2018, cybercriminals gained access to an internal BA application by abusing compromised credentials for a Citrix remote access gateway. This hack was used as a toe-hold to hack more sensitive systems in a series of attacks that allowed cybercriminals to edit a JavaScript file on BA’s website, allowing fraudsters to exfiltrate sensitive cardholder data to a rogue domain controlled by the crooks, an ICO investigation found.

Client-side application security

Organizations faced with the challenge of preventing Magecart-style skimmers from covertly running on their sites and exfiltrating data can use behavior-based detection from Jscrambler to mitigate the threat.

Clients of the Jscrambler client-side protection platform include banks worldwide, a major airline in the EU, a top retailer in the US, and three top US-based entertainment companies.

Other clients operate in industries including financial services, payments, e-commerce, travel and logistics, gaming and gambling, and healthcare. Clients use the technology to guard against data leaks, regulatory infractions, and integrity violations.

Client-side Protection platform


Jscrambler has been focused on client-side security since 2010. Jscrambler provides multiple layers of client-side protection – from making code resilient to tampering and interference with scripts supplied by third-party tools and risky vendors.

The technology allows clients to protect user data and comply with regulatory standards such as HIPAA (the US Health Insurance Portability and Accountability Act) and GDPR (General Data Protection Regulation) as well as standards including PCI DSS.

With Jscrambler, your teams are free to take full advantage of third-party scripts and client-side innovation, confident in the knowledge that you are heavily protected from cyber attacks, sensitive data leakage, misconfigurations, and IP theft.

Jscrambler’s client-side protection platform allows businesses to concentrate on innovation while staying compliant, secure, and safe from data breaches and client-side attacks that are being powered by AI.

Jscrambler Achieves PCI-DSS Version 4.0 Compliance

PORTO, Portugal, Tuesday, December 19th, 2023


Jscrambler, the pioneering platform for client-side protection and compliance, today announces it has been assessed as compliant with PCI DSS v4 following an external assessment by Advantio, a leading Qualified Security Assessor (QSA), signifying the high-security standards Jscrambler’s platform and environment meets. This achievement, ahead of the April 1st, 2024 deadline for meeting the new standard underpins Jscrambler’s dedication to protecting its customers’ sensitive data and ensuring the security of their financial transactions. 

To be assessed as compliant with PCI DSS, companies must demonstrate the ability to protect both their assets and their clients. While Jscrambler does not store, process, or transmit cardholder data, Jscrambler does provide an agent that is present on customer payment pages. Service providers that can affect the security of cardholder data are considered in the scope of PCI DSS v4

“We believe that ideally, every location where a browser loads JavaScript on the payment page should undergo a service provider assessment because that JavaScript can be compromised to leak payment card data,” explains Rui Ribeiro, CEO and Co-founder of Jscrambler. “As a service provider to merchants who have PCI DSS obligations, we are focused on creating a secure environment for our customers’ financial transactions and their business. This means not only understanding and helping them to meet compliance mandates but also having full confidence in our ability to meet the requirements as well.”

He continued: “Everyone that plays a role in the payment’s ecosystem, and the solutions and applications that process these payments, have a shared responsibility in securing transactions so that the consumers can have confidence that their data and privacy are taken seriously. Whether you are a solution vendor, service provider, PSP, or merchant, it is imperative that you take the appropriate measures to validate the security of, and mitigate any risks associated with, online payments and payment pages.”

The Payment Card Industry Data Security Standard (PCI DSS) is a global standard that provides a set of requirements for protecting Cardholder Data. Version 4 represents the state of the art in terms of cyber security and demonstrates a commitment to ensuring the protection of customer’s data. The requirements listed in PCI DSS v4 will mandate that the businesses that handle (store, process or transmit) or who could affect the security of payment data implement a set of controls (technical, physical and human) to protect such data. PCI DSS compliance must be renewed annually to ensure continued compliance with the security standard. This is an ongoing commitment that reflects dedication to data protection and transaction security. 

New PCI DSS v4 Requirements Attempt to Mitigate Expanding Surface Area Risk

JavaScript has become the building block of nearly every modern-day web page. While it can serve many purposes, it can also deliver unprecedented and sometimes unseen security risks that last for months, should it not be monitored properly. The introduction and widespread use of third-party JavaScript is one example, as online businesses increasingly struggle to maintain complete visibility and control over these scripts. Earlier this year, Jscrambler found that 80% of the 20 most highly trafficked US e-commerce websites had an average of 148 JavaScripts on their payment pages. For these reasons and more, PCI DSS has included specific requirements (6.4.3 and 11.6.1) designed to minimize this increasing attack surface area, manage all JavaScript executing on payment pages, and detect any tampering or unauthorized changes to the payment page that can result in leaking of the cardholder data. 

Jscrambler is fully committed to PCI DSS, with its Co-founder and CTO, Pedro Fortuna, serving as a member of the PCI SSC Board of Advisors and recently having been added as a Principal Participating Organization. With Jscrambler having been externally assessed as compliant with PCI DSS v4, clients of Jscrambler can reliably utilize the Jscrambler Client-Side Protection Platform to both protect cardholder data that is entered into a customer’s web page from skimming attacks and to meet the PCI-DSS v4 requirements 6.4.3 and 11.6.1. These new requirements are currently considered ‘best practice’ until April 2025 when they become mandatory. Implementing the new requirements will ensure that merchants can prevent and detect unauthorized changes to JavaScript code. For this reason, service providers and merchants must prepare for PCI DSS v4.0 as they can impact the security of the cardholder data environment (CDE). 

To find out more about the potential impacts of first and third-party JavaScript on payment pages, read Jscrambler’s most recent blog post, Are Non-PCI Compliant Scripts Putting Your Business at Risk?

Customers, prospects, and partners may receive the Jscrambler Attestation of Compliance (AOC) report upon request by contacting their account manager.

The QSA company in charge of this project has been Advantio, an Integrity360 company, with over ten years of experience providing PCI consultancy and formal validation services worldwide via a large team of multilingual subject matter experts.

“Jscrambler offers a robust security solution, setting a high standard and expecting nothing less. We believe that merchants and service providers utilizing Jscrambler will find it effortless to maintain the integrity of their websites without compromising functionality,” said Manuel Fernandez, Regional Sales Director, Advantio, an Integrity 360 company. “We highly recommend every service provider delivering a script on a merchant’s site to consider the potential impact on the Cardholder Data Environment. Compliance with PCI DSS version 4.0 is imperative for ensuring a secure environment.”

Additional Resources

About Jscrambler 

Jscrambler is the leading Client-Side Protection and Compliance Platform. We were the first to merge advanced polymorphic JavaScript obfuscation with fine-grained third-party tag protection.

Our integrated solution ensures a robust defense against current and emerging client-side cyber threats, data leaks, misconfigurations, and IP theft, empowering software development and digital teams to innovate securely.

Code Integrity and Webpage Integrity

The Jscrambler Code Integrity product safeguards first-party JavaScript through state-of-the-art obfuscation and exclusive runtime protection.

The Jscrambler Webpage Integrity product mitigates threats and risks posed by third-party tags all while ensuring compliance with the new PCI DSS v4 standard. With Jscrambler, businesses adopt a unified, future-proof client-side security policy all while achieving compliance with emerging security standards.

Trusted by digital leaders including Netflix, SAP, Electronic Arts, Canal+, Gap, and Swisscom, Jscrambler gives businesses the freedom to innovate securely.

Are Non-PCI Compliant Scripts Putting Your Business at Risk?

In an ideal world, websites would be secure, bullet-proof, and impregnable – whatever you want to call it. But the real world is complicated.

Websites are built differently these days. They’re dynamic, not static. The business intelligence behind them has moved from web servers, owned and managed by businesses, to consumer web browsers, powered by JavaScript, distributed APIs, and microservices. 

JavaScript has become ubiquitous due to its versatility. However, its inherent security weaknesses have made it a prime target for cybercriminals. These wily and well-resourced adversaries will stop at nothing to get their hands on customer data. 

Given that payment data is particularly prized. It can be sold on or monetized via payment fraud or identity theft, so should all scripts come from a PCI-compliant source? And how should merchants verify that their service providers have taken all the necessary steps to ensure their scripts are secure?

In this article, we look at:

  • How the web moved from static to dynamic pages

  • Why JavaScript became ubiquitous

  • Why JavaScript became a security vulnerability

  • What are the new requirements to protect against and detect e-skimming?

  • How do payment pages fit into the cardholder data environment?

  • What are the risks of each type of payment page?

  • How to mitigate the risks of JavaScript on payment pages

  • How can Jscrambler help?


Why are non PCI compliant scripts putting your business at risk?


How the web moved from static to dynamic pages

In the early years of the web, pages were built entirely in HTML. They looked like the equivalent of printed pages and were static. Each click brought up a new page. Even a small change to the page meant that the entire page had to be reloaded. 

Behind the scenes, this was powered by one-to-one interactions between web browsers and web servers. Sending or retrieving data, either from within an organization or from across the web, was mediated by a web server. This made it easy to create webpages, but the user experience was stop-start.

In 1995, Sun Microsystems released Java, which enabled the dynamic exchange of data over the web. By 1999, Internet Explorer 5 began to dynamically update the news stories on the MSN homepage. This functionality was gradually adopted by nearly all browsers. And the web moved from static to dynamic pages.

Why JavaScript became ubiquitous  

JavaScript has come to power the web due to its versatility. It provides a form to collect data, enables functionality, such as tag managers or content management systems, and can be used to build entire websites. 

So much so, more than 99% of all websites use JavaScript in some form, either from code developed in-house (first party) and/or embedded from third-party vendors. This includes the payment pages of e-commerce websites. 

Jscrambler’s research found that 80% of the 20 most highly trafficked US e-commerce websites had more than 130 scripts on average loaded on their payment pages, of these, 97% were third-party scripts.

Why JavaScript became a security vulnerability  

Any JavaScript running on a web page can access all data entered into form fields on that page. This makes payment pages susceptible to e-skimming attacks, also known as formjacking or Magecart attacks

These client-side attacks occur when cybercriminals inject malicious code onto the payment page of an e-commerce website to harvest sensitive payment card data. This includes the account number, expiration date, and 3 or 4-digit security code, which criminals can monetize. Either by using it to make unauthorized, fraudulent purchases for goods to re-sell for cash. Or by selling the data to other criminals.

Such attacks are pernicious as they can remain undetected for many months. They’re completely silent and don’t interfere with the payment process. The attack surface is also broad. Criminals can hack the website directly or attack via the supply chain, compromising either first-party or third-party JavaScript. They end up being consequences for failed compliance.

What are the new requirements to protect against and detect e-skimming?

Given the ubiquity and innate security vulnerabilities of JavaScript on payment pages, the PCI Security Standard Council (PCI SSC) published an updated version PCI Data Security Standard (PCI DSS) in March 2022. Version 4.0 of the PCI DSS contains two new requirements to protect against and detect these e-skimming attacks on payment pages.

The first requirement (6.4.3) is designed to minimize the attack surface and manage all JavaScript present in the payment page. The second requirement (11.6.1) aims to detect tampering or unauthorized changes to the payment page and generate an alert when changes are detected.

Service providers as well as merchants must prepare for PCI DSS v4 as they can impact the security of the cardholder data environment (CDE).


[LEARN MORE] Checklist PCI DSS v4 Requirements for Payment Pages: How to Comply

How do payment pages fit into the cardholder data environment?

PCI DSS v 4.0 defines a payment page as “a web-based user interface containing one or more form elements intended to capture account data from a consumer or submit captured account data.”

It continues that the payment page can be rendered as any one of the following:

  • A single document or instance

  • A document or component displayed in an inline frame (iframe) within a non-payment page

  • Multiple documents or components each containing one or more form elements contained in multiple inline frames (iframe) within a non-payment page

The definition is broad to allow for the various ways in which e-commerce merchants implement payment pages. They can either store, process or transmit data on the payment page themselves. 

Or post the sensitive card data entered by their customers directly to their payment service provider (PSP). This can happen either directly on the page or via a page embedded in one or more iframes.

The security of payment pages is important because they fall within the scope of PCI DSS requirements as “system components […] that could impact the security of the cardholder data environment (CDE).” “Systems components” is further defined in PCI DDS v 4.0 to include “network devices, servers, computing devices, virtual components, cloud components, and software.”

What are the risks of each type of payment page?

There are pros and cons to each type of payment page. With an iframe, the payment form is integrated seamlessly into the merchant’s website, so customers never leave the site during the payment process. This may help reduce cart abandonment rates and increase conversion, as customers feel more secure and confident in the checkout process. 

iframes also make it easier to embed external (third-party) content on pages, reuse code across multiple pages, and sandbox content for improved security. Specifically, iframes could make it more difficult, although not impossible, to steal sensitive cardholder data. That’s because JavaScript running on the main checkout page cannot generally access data entered in an iframe payment page.

That being said, criminals have found ways to circumvent the security offered by iframe payment pages. For example, frame overlay attacks, where criminals put their own payment page on top of that of the merchant or PSP. Or fake payment pages, where they put their payment page before that of the merchant of PSP in the checkout process. 

Irrespective of what type of payment page a merchant uses, they are exposed to risks each time a service provider adds JavaScript to the CDE.

How to mitigate the risks of exposed JavaScript on payment pages

Given that any JavaScript that’s on the payment page can read and steal cardholder data many QSAs would say that every source of JavaScript loaded must be compliant with PCI DSS itself. However, that isn’t the general practice in the market. It is perhaps why the PCI SSC felt the need to add these two new requirements to PCI DSS v 4.0.

Managing the risk associated with JavaScript that executes in your customers’ browsers is already part of PCI DSS. In version 3 it certainly should have formed part of an entity’s risk assessment and, depending on an assessor’s view, potentially be included in the PCI DSS scope. 

In version 4.0, the two new requirements are currently indicated as a best practice and will become a requirement from 01 April 2025. So, when selecting a vendor and using their scripts, they must follow good security practices and be PCI-compliant as a best practice.

Jscrambler’s Client-Side Protection Platform is a holistic solution to detect and block malicious behavior on client-side web applications in real-time. It prevents leaking or scraping of sensitive data, plus protects against supply chain attacks. It is provided as a JavaScript agent that’s loaded into the customer’s browser so, of course, Jscrambler is compliant with PCI DSS v 4.0 and undergoes an annual QSA assessment to validate this.

How can Jscrambler help?

Jscrambler addresses both new PCI requirements (prevention and detection) concerning attacks on payment pages. What’s more, as the payment page is likely to include other JavaScript libraries, Jscrambler provides a smoother and easier way to manage the integrity of third-party code, compared to Content Security Policy (CSP) and Subresource Integrity (SRI).

Features include:

1. First-party code hardening and obfuscation

Obfuscation and protection of the first-party code that the Payment Service Providers supply to Merchants, further enhancing the defense against tampering with payment pages.

2. Webpage inventory 

Complete visibility of every script and network request on your website. Simplifies the identification of malicious client-side behavior and vetting of resources.

3. Third-party management

Simple onboarding and vetting of third-party scripts, with full observability of each script and a powerful rules engine that can be used to control its behavior.

4. User data management

Dashboard with details of how user data is being handled on the client-side, with insights into possible data leakage.

5. Webpage threat mitigation

Powerful and granular rules engine that blocks any script in real-time, if it exhibits malicious or prohibited behavior (e.g., form-jacking, DOM tampering, skimming, data leakage).

Jscrambler’s Client-Side Protection Platform helps companies comply with the new PCI DSS v4.0 requirements easily without breaking the functionality of payment pages.

In addition to functionality, every service provider, who provides a script on a merchant’s site that could impact the security of their CDE, should also be compliant under PCI DSS 4.0. Jscrambler recently achieved attestation against PCI DSS v 4.0.

18 Cybersecurity and Hacker Movies and Series to Watch this December

The top 18 cybersecurity and hacker movies and series list is a curated selection by the Jscrambler team.

If you are in the mood for suspense, hearts pumping, and juicy fiction (that could be inspired by a true story), a good movie or TV show about hacking and cybersecurity never disappoints.

From gripping cybercrime stories to eternal classics and less-known gems, you will not regret spending a few afternoons with these thrilling movies and series. Dive into our selection of the best cybersecurity and hacker movies and series of all time!

1. WarGames (1983)

A young computer enthusiast unintentionally hacks into a military central computer. David provokes military mayhem at an international level.

WarGames are on the other side of how real-life hacking occurs. Instead of hyperbolizing the capabilities of a hacking attack, it portrays hacking as a simple black-and-green screen.

WarGames is a 1983 American techno-thriller film directed by John Badham. The cast includes names such as: 

  • Mattew Broderick

  • Ally Sheedy

  • Dabney Coleman

  • Barry Corbin

  • Juanin Clay

WarGames official trailer

2. Sneakers (1992)

Computer hacker Martin is challenged to steal a powerful hacking tool and doesn’t know what to do. It’s a movie with turns and plot twists for the thriller lovers.

Directed by Phil Alden Robinson, Sneakers is a 1992 film full of puzzles, mind games, and moral dilemmas. The cast includes names such as: 

  • Robert Redford

  • Sidney Poitier

  • River Phenix

  • Dan Aykroyd

  • Ben Kingsley

  • David Strathairn

Sneakers official trailer

3. Hackers (1995)

Hackers became a cult classic over the years. The characters use hacking techniques to obtain what they need, from phishing to password cracking (a classic!) and network scanning.

The real-life hacking hyperbolizes the capabilities of a hacking attack through coding prodigies able to design enormous cyber-terrorist attacks.

Directed by Iain Softley, Hacker captures the early internet atmosphere and introduces the cyberpunk aesthetic. The cast includes names such as: 

  • Angelina Jolie

  • Jonny Lee Miller

  • Matthew Lillard

  • Renoly Santiago

Hackers official trailer

4. Ghost in the Shell (1995)

Motoko Kusanagi runs the Public Security Section 9 and leads the hunt for a well-known hacker named Puppet Master.

Ghost in the Shell is a cyberpunk anime based on the homonymous manga by Masamune Shirow.

Ghost in the Shell is a 1995 animated neo-noir cyberpunk thriller directed by Mamoru Oshii.

Ghost in the Shell official trailer

5. The Net (1995)

A computer programmer falls into the midst of a dangerous conspiracy by cybercriminals. The Net is a suspense thriller with strong emotions.

Directed by Irwin Winkler, The Net is a compelling story about how the Internet controls people’s lives. The cast includes names such as: 

  • Sandra Bullock

  • Jeremy Northam

  • Diane Maker

  • Dennis Miller

  • Margo Winkler

The Net official trailer

6. 23 (1998)

23 explores the pioneering beginning of many civilian hackers who started investigating the capabilities of new technological devices in the 1980s. This thriller is about Karl Koch, a real-life hacker who hacks the global data network, the previous version of the Internet. 

Karl Koch works for the KGB and defines the beginning of electronic espionage through computers rather than in persons by mysterious spies, such as 007 agents.

Directed by Hans-Christian Schmid, 23 is a 1998 thriller. The cast includes names such as: 

  • August Diehl

  • Fabian Busch

  • Dieter Landuris

23 official trailer

7. The Matrix (1999)

The Matrix is an action-packed hacker movie that transcends reality.

The hacking in the Matrix movie comes in binary code displayed on a screen.  The translation occurs into intricately choreographed action sequences with astonishing special effects.

The Matrix is a 1999 science fiction action film directed by the Wachowskis. The cast includes names such as: 

  • Keanu Reeves

  • Carrie-Anne Moss

  • Gloria Foster

  • Marcus Chong

The Matrix official trailer

8. Swordfish (2001)

Swordfish is about how computer cracker Stanley joins one of the many heists to make billions of dollars from unused government funds. The coding in this popcorn movie is visually appealing and looks authentic. 

Directed by Dominic Sena, Swordfish is a 2001 American action techno-thriller. The cast includes names such as: 

  • John Travolta

  • Hugh Jackman

Swordfish official trailer

9. Inception (2010)

Dom Cobb can penetrate people’s dreams to steal secrets from them. Inception is about his mission to implant an idea in businessman Robert Michael Fischer. It is a different type of hacking, where hackers hack into people’s dreams to access their brains instead of taking secrets.

Inception is a 2010 science fiction action film written and directed by Christopher Nolan. The cast includes names such as: 

  • Leonardo DiCaprio

  • Joseph Gordon-Levitt

  • Cillian Murphy

  • Tom Hardy

  • Elliot Page

  • Marion Cotillard

“A one-of-a-kind mind-blowing masterpiece!” adrien_ngoc_170, 11 March 2019.
Source: IMDb reviews.

Inception official trailer

10. The Girl with the Dragon Tatoo (2011)

Based on the homonymous novel by Stieg Larsson, The Girl with the Dragon Tatoo shows a more authentic portrayal of hackers and hacking abilities mixed with cyberpunk elements.

Lisbeth Salander is a security expert and skilled hacker with an obscure past.

The Vanger family is investigating the disappearance of a family member. It is the perfect formula for a movie full of plot twists.

It was directed by David Fincher with a screenplay by Steven Zaillian. The cast includes names such as: 

  • Rooney Mara

  • Daniel Craig

  • Robin Wright

  • Stellan Skarsgård

  • Christopher Plummer

The Girl with the Dragon Tatoo official trailer

11. Open Windows (2014)

Open Windows is a creative technological movie. When Jill’s cellphone is hacked, the hacker can remotely turn on its camera and microphone.

Open Windows is a 2014 found footage techno-thriller directed by Nacho Vigalondo. The cast includes names such as: 

  • Elijah Wood

  • Sasha Grey

  • Nacho Vigalondo

Open Windows official trailer

12. Who Am I (2014)

Benjamin aims to make a name for himself in the hacker community. To achieve this, Benjamin joins a group of tech masters to form a hacker group with one mission: to become the best of the best.

Who Am I is a techno-triller about a German hacker full of tech scenes directed by Baran Bo Odar. The cast includes names such as:

  • Tom Schilling 

  • Elyas M’Barek

  • Wotan Wilke Möhring

  • Trine Dyrholm

Who Am I official trailer

13. The Signal (2014)

The Signal puts the hacking theme into a scenario of three sets: thriller, science fiction, and arthouse. 

Hacking is not the theme, but it is significant because it shows the students’ ability to counterattack the hacker by tracking down his position. Directed by William Eubank, The Signal’s cast includes names such as: 

  • Laurence Fishburne

  • Brenton Thwaites

  • Olivia Cooke

  • Beau Knapp

The Signal official trailer

14. Blackhat (2015)

Nick Hathaway is the hacker helping his American and Chinese counterparts hunt down a cyber-terrorist crime organization across the globe.

Backhat thrills its audience with real-world applicable fears. The spotlight is on the cyber-connectivity of the world and its risks and vulnerabilities.

Blackhat is a 2015 American action thriller film produced and directed by Michael Mann. The cast includes names such as:

  • Chris Hemsworth

  • Tang Wei

  • Viola Davis

  • Wang Leehom

Blackhat official trailer

15. Mr. Robot (2015-2019)

Cinematic and creative, Mr. Robot is a stand-out series with top-quality performances. Elliot is a cyber-security company programmer by day and a vigilante hacker by night.

Available on Google Play, Apple TV, Vudu, Prime Video, and Netflix in some countries.

All episodes were directed by Sam Esmail. The cast includes names such as:

  • Rami Malek

  • Portia Doubleday

  • Carly Chaikin

  • Christian Slater

“Now that it’s over, I am confident in giving it a 10”. DrunkenDeGroot, 26 December 2019.

Source: IMDb reviews

Mr. Robot official trailer (season 1)

16. Anon (2018)

Anon’s action happens in a futuristic society where privacy doesn’t exist.

The hacking elements are relevant to show the importance of private citizens’ data to control society and increase power. The cyber attacks target the eyesight of individuals rather than their devices.

Anon is a 2018 British-American science fiction thriller directed by Andrew Niccol. The cast includes names such as:

  • Clive Owen

  • Amanda Seyfried

  • Colm Feore

  • Iddo Goldberg

Anon official trailer

17. The Billion-Dollar Code (2021-ongoing)

The introduction of the World Wide Web brought together digital artists and Berlin hackers in the 1990s, but fast-forward to 2014. Two cutting-edge pioneers are in court with a US tech giant over the Google Earth algorithm. It’s a tale of raves, techno, and a quirky take on the patent dispute between Terravision and Google.

Available on Netflix. The cast includes names such as:

  • Marius Ahrendt

  • Leonard Scheicher

  • Seumas Sargent

  • Lavinia Wilson

The Billion-Dollar Code official trailer

18. Reality (2023)

An American ex-intelligence specialist has received the lengthiest sentence for disclosing government information to the media without authorization.

The information released concerned Russian interference in the 2016 US elections, and this is the motto for a crime drama film based on an FBI interrogation.

Reality is a 2023 American crime drama directed by Tina Satter. The cast includes names such as:

  • Sydney Sweeney

  • Josh Hamilton

  • Marchánt Davis

  • Benny Elledge

The Reality official trailer

3 Notorious Real-life Hackers

1. Kevin Mitnick

Throughout his hacking career, Mitnick never exploited the access and data he obtained. It is believed that Kevin’s goal was to control Pacific Bell’s network to prove it could be done.

2. Anonymous

Anonymous hacking actions are rooted in the concept of social justice. It started in 2003 on 4chan message boards.

3. Adrian Lamo

Lamo used to hack systems and notify the press and his victims. Sometimes, he would help clean up the mess to improve their security.

Hackers are a Real Cyber Threat to Business Security

Hackers can cause financial and reputational damages in several ways by exploiting business security vulnerabilities, from customers no longer trusting the business to losing competitive advantages.

The most common cyber threats today are

  • Phishing attacks.

  • Malware attacks

  • SQL injection attacks

  • Denial of service attacks

  • Insider threats

Overall, cybercriminals look for access to information and data on businesses, employees, and customers. They might do this by

  • Unauthorized access to hardware, computers, and mobile devices.

  • Infecting computers with malware.

  • Attacking technology or websites.

  • Attacking third-party systems.

  • Gaining access to information through customers or employees.

Myth buster: 10 of the most common PCI DSS myths busted

The first version of the PCI DSS was published almost 20 years ago. Since then, many myths and misconceptions have arisen around the 12 requirements, describing how card data must be stored, processed, and transmitted. We dispel some of the most common ones.

10 PCI DSS myths explained

1. We don’t take enough card payments, PCI DSS doesn’t apply to us

Variations of this myth are that small merchants don’t need to be compliant. Or that small merchants don’t need to worry about PCI DSS until they start processing a certain number of card payments. 

There’s also confusion around the types of cards accepted. For some businesses, a payment card equals a credit card. They only accept debit or prepaid cards. Or they don’t accept AMEX cards, so they think – mistakenly – that PCI DSS doesn’t apply to them.

In fact, business size doesn’t matter. Nor is the number or nature of card payments accepted. Simply put: if your business accepts cards, then PCI DSS applies.

2. We don’t deal directly with consumers, so we’re not a target 

Sadly, criminals aren’t choosy about the nature of their customers. They could be consumers, other businesses, large corporations, multinationals, or even government departments. 

Nor are they choosy about the nature of your business. They don’t care whether you’re a retailer, non-profit organization, charity, educational institution, or government agency.

Card data is card data. Criminals can sell stolen data on underground forums. They can use it themselves to create fake cards to withdraw cash from ATMs. Or buy things to sell for profit.

Generally, if data has value to you or your customers. Then, you can almost guarantee it has value to criminals, too, so protect it.

3. We don’t sell online, PCI DSS doesn’t apply to us 

PCI DSS applies to all businesses that accept cards, regardless of how they trade.

Believe us, criminals have tried and trusted ways of attacking all sales channels. Whether it’s SQL injection or man-in-the-middle attacks in e-commerce. Or terminal swap-out fraud in physical stores. Their greed for card data is matched only by their cunning.

[LEARN MORE] Three things you need to know about PCI DSS v4.0

4. We’re able to store any data we want, and our customers consent to this 

A variation of this myth is that card schemes, PCI or some external organization is making businesses store cardholder data. The reverse is true.

Businesses don’t own customer card data. Card schemes and the PCI SSC, the body that administers PCI DSS, strongly discourage the storing of sensitive cardholder data. 

There’s no good reason for you to store data from a card’s magnetic stripe or chip. But if your business bills customers regularly or refunds customers’ cards and retains card numbers and expiry dates to do so, protect this data. This is where encryption and/or tokenization technologies come into play. 

In summary, if you don’t need it, don’t store it. If you do, protect it.

5. We don’t work in the IT department, PCI DSS is not my job 

The truth of the matter is that data security is everyone’s job. Just as adhering to HR policies and brand usage guidelines is everyone’s job, no matter where they work in an organization.

The IT department may lead on certain technical and operational aspects of PCI DSS, but it’s a business-wide responsibility. 

Firstly, because how your business stores, processes, or transmits card data touches almost every aspect of the customer journey. Everything from how you receive orders and issue refunds to how you identify new versus repeat customers.

Secondly, because 37% of retail sector data breaches involved payment data. And 100% of data breaches had a financial motive, according to a recent Verizon report. The impact of a data security breach is financial and reputational, which affects your business as a whole.

6. We’re compliant with PCI DSS, we’re secure 

Variations of this myth are that our business is PCI DSS-compliant, so it’s protected from hackers or ‘hacker-proof’.

Point-in-time compliance doesn’t guarantee ongoing security. To prove this point, only 29% of companies were still PCI DSS-compliant less than a year after validation, a Verizon report showed. That’s quite simply because security is not a one-and-done activity, but more a continuous process. 

Anything can change in your business, that of a trusted partner or third party, in the market or even with the PCI DSS standard. Remaining secure requires ongoing vigilance. And the right people, processes, and technology to back this up.

7. We’ve completed a PCI DSS Self-Assessment Questionnaire (SAQ), and we’re compliant 

SAQs, vulnerability scans, pen tests, and so on are merely tools. Your PCI DSS scope and what you must do to evidence compliance depends on your business and how you accept card payments. 

It also changes over time. Any self-assessment, scan, or test is only a snapshot of when it was completed.

It’s also a myth to think that your business is compliant if it meets most criteria. That’s like thinking that you’re mostly pregnant. Either you are, or you’re not. There’s no mid-point.

8. We’ve taken out cyber insurance, and we’re protected

Taking our cyber insurance merely helps your business cover some of the costs of a cyber incident or breach. This includes paying for investigators, communication, and legal experts, plus the costs of notifying and refunding customers affected. It won’t necessarily protect your business from a data breach. Or make it PCI DSS-compliant or secure.

Your card acquirer or payment service provider will still hold you responsible if you suffer a card data breach. Or are found to be non-compliant with PCI DSS. They could fine you or terminate your card acceptance. You can’t transfer this risk through the purchase of insurance.

9. We’ve outsourced card processing, we’re protected 

It probably won’t surprise you at this stage, but PCI DSS compliance is not as simple as that. Outsourcing card processing doesn’t automatically make a business secure or compliant. 

You must consider how your business secures card data throughout the customer relationship. This includes processing refunds, reversals, and chargebacks. You must also do due diligence on outsourcing partners and their PCI status to ensure they’re compliant. 

Finally, be warned. While your business can outsource the responsibility for performing a task, you can’t outsource the liability, if things go wrong.

10. We already work with a number of security vendors, so we’re protected

There are no silver bullets in security. Working with too many vendors and products can be as bad as working with too few if they’re the wrong ones.

So, understand the types of vendors you’re working with and the services they provide. Are they terminal vendors, hosting providers, software-as-a-service vendors, or resellers?

Ensure they’ve taken appropriate steps to protect card data. The general areas to quiz them on include the security of their product or service, how and where it’s installed, whether they provide ongoing support and maintenance, and what happens if there’s a data breach.

Conclusion

Twelve high-level PCI DSS requirements and hundreds of sub-requirements over nearly 20 years can create many myths, misconceptions, and misunderstandings. Unsurprisingly, businesses struggle to understand how they can best secure card data and become PCI DSS compliant.

Jscrambler goes one step further than the new requirements and can be configured to automatically block all attempts to skim cardholder data from e-commerce transactions.

[LEARN MORE] Free tool to comply with PCI DSS v4.0 by Jscrambler


Jscrambler’s free PCI DSS 4.0 compliance tool helps Merchants achieve compliance with requirements 6.4.3 and 11.6.1 of PCD DSS v4.0 and QSAs to validate compliance.

Unit Testing Angular App

In this tutorial, we’ll learn how to unit test a simple functional form in an Angular app. We’ll be creating the form using Reactive forms, we’ll be adding a couple of fields, and validating and submitting the form. We’ll go over how to unit-test the form-related features and code.

In one of our previous tutorials on Angular unit testing, we learned how to start with Angular unit testing. I would recommend reading it before you start with this tutorial because it would give you a basic understanding of Angular unit testing.

Getting Started with Unit Testing Angular App


I’ll walk you through the code so that you don’t feel alienated when we start with unit testing the code. Our approach will be to understand what the code does and then write a unit test for it.

We are using Angular Material UI component for this project. Each and every component that is being used for this project is imported into the `app.module.ts` file.

Creating Angular app

Start by creating an Angular project from scratch using the Angular CLI which you can install using `npm`.

bash
npm install -g @angular/cli


After the Angular CLI is installed create your Angular boilerplate project using

bash
ng new form-app


We are using Angular Material UI for the project. You can add Material UI components to the project using the following command:

bash
ng add @angular/material


By default, you have `AppComponent` inside the project. You can remove the existing code from the `app.component.html` file leaving just the route outlet. Here is how the `app.component.ts` file looks:

html
<router-outlet></router-outlet>


Now create a new component called `HomeComponent`.

ng g component home


This will create a new folder `src/app/home` with the required component files inside it.

Modify the routing file to display the Home Component when the app loads. Here is how the `app-routing.module.ts` file looks:

typescript
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';

const routes: Routes = [{
  path: "", component: HomeComponent
}];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }


Now if you run your application it should load the Home component by default.

Creating Angular Reactive Forms


The form that we will be unit testing is being implemented in the `HomeComponent` inside `src/app/home` folder. The form design is created using Angular material components and can be found inside the `home.component.html` file.

Here is what the `home.component.html` file looks like:

html
<mat-card style="margin: 100px;background-color: beige;">
  <mat-card-content>
    <form style="    display: flex;
        flex-direction: column;
        align-items: center;" [formGroup]="profileForm" (ngSubmit)="onSubmit()">
      <mat-form-field appearance="fill">
        <mat-label>Enter name</mat-label>

        <input id="firstName" matInput formControlName="firstName" placeholder="enter your name">
        <mat-error *ngIf="f && f['firstName'] && f['firstName'].errors?.['required']">
          Name is required.
        </mat-error>
      </mat-form-field>

      <mat-form-field appearance="outline">
        <mat-label>Email address</mat-label>
        <input matInput formControlName="emailAddress" placeholder="enter your email address">
        <mat-error *ngIf="f && f['emailAddress'] && f['emailAddress'].errors?.['required']">
          Email address is required.
        </mat-error>
      </mat-form-field>

      <mat-form-field appearance="outline">
        <mat-label>Phone Number</mat-label>
        <input matInput formControlName="phoneNumber" placeholder="enter your phone number">
        <mat-error *ngIf="f && f['phoneNumber'] && f['phoneNumber'].errors?.['required']">
          Phone number is required.
        </mat-error>
      </mat-form-field>
      <button mat-raised-button color="primary">Save</button>

    </form>
  </mat-card-content>
</mat-card>


Now, on loading the page we have a feature where we’re showing some default data when the form loads. For that, we have already defined a default data object in our `home.component.ts` file and we are setting the data inside the `ngOnInit` hook.

Here is how the `home.component.ts` file looks:

typescript
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
})
export class HomeComponent {

  defaultData : any = {
    firstName : "Roy",
    emailAddress : "[email protected]",
    phoneNumber : "+919895590754"
  }
  profileForm :FormGroup= new FormGroup({});

  get f() { return this.profileForm.controls; }

  constructor(private _formBuilder: FormBuilder){}
  ngOnInit(): void {
    this.profileForm =  this._formBuilder.group({
      firstName: [''],
      emailAddress: [''],
      phoneNumber: ['']
    })
    this.profileForm.setValue({firstName : this.defaultData.firstName ,emailAddress :
this.defaultData.emailAddress, phoneNumber : this.defaultData.phoneNumber})
  }
  onSubmit() {
    try{
    } catch(error){
    }
  }
}


For the above material UI component to work you need to import the component inside the `app.module.ts` file.

typescript
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatIconModule } from '@angular/material/icon';
import { MatCardModule } from '@angular/material/card';
import { ReactiveFormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    MatFormFieldModule,
    MatInputModule,
    MatIconModule,
    MatCardModule,
    MatButtonModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Now if you run the application you’ll be able to see the default data being populated in the application form.

Unit Testing ngOnit


When we created our Angular component the corresponding test file was created by default. In our case, there will be a `home.component.spec.ts` file.

You can try running the unit test for the Angular project using `ng test` which should run the unit test with some errors. Since our `home.component.ts` is using some Angular material UI imports, those need to be imported in the test file too.

Here is how the `home.component.spec.ts` file looks with the required imports inside the `beforeEach` block.

typescript
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { HomeComponent } from './home.component';
import { MatCardModule } from '@angular/material/card';
import { MatFormFieldModule } from '@angular/material/form-field';
import { ReactiveFormsModule } from '@angular/forms';
import { MatInputModule } from '@angular/material/input';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

describe('HomeComponent', () => {
  let component: HomeComponent;
  let fixture: ComponentFixture<HomeComponent>;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [HomeComponent],
      imports: [BrowserAnimationsModule, ReactiveFormsModule, MatInputModule, MatFormFieldModule, MatCardModule]
    });
    fixture = TestBed.createComponent(HomeComponent);
    component = fixture.componentInstance;
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

Now before we write out the unit test case, let’s try to understand what is already there inside the `home.component.spec.ts` file.

describe block

This block is used to group the unit test cases. In this particular case, we have grouped the Home component test cases under `describe(‘HomeComponent’)` block

beforeEach block

This block is executed before each unit test case is run. Inside this block, we are configuring the test bed with the required imports for the test case to run. You can also see that we are creating a new component instance each time

it block

This block defines the particular unit test case.

The default test case `it(‘should create’` tests whether the component loaded without any errors and it confirms it by checking if its value is true or not.

Now let’s write our test case for checking if the default value is being in the `ngOnInit` hook. Start by writing the `it` block.

  it('should set default values', () => {
    
  })


`HomeComponent` the default value is picked up from the variable `defaultData` so in the component instance let’s set the `defaultData`.

typescript
component.defaultData = {
      firstName : "Tim",
      emailAddress : "[email protected]",
      phoneNumber : "+919895590754"
    }


Once the variable is set you need to run the Angular component change detection using the following command

typescript
fixture.detectChanges();


Now if all goes well then the Reactive form’s value would be set as per the `defaultData` value. You can check by checking the value of the `profileForm` from the component instance.

typescript
expect(component.profileForm.getRawValue()['firstName']).toEqual(component.defaultData['firstName']);


Here is the complete unit test case:

typescript
  it('should set default values', () => {
    component.defaultData = {
      firstName : "Tim",
      emailAddress : "[email protected]",
      phoneNumber : "+919895590754"
    }
    fixture.detectChanges();
    expect(component.profileForm.getRawValue()['firstName']).toEqual(component.defaultData['firstName']);
  })


Now before running the test case, delete the spec file`app.component.spec.ts`. That’s the spec file for `AppComponent` with boilerplate code. Try running the unit test cases using `ng test` and it should return a successful result.

Adding Validation to Form


Currently, the form doesn’t have any validations as such. We’ll just add the required field validation to our form. Inside `ngOnInit` where you have defined the `profileForm` add required validation to each of the form fields.

Here is the modified `home.component.ts` file:

typescript
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
})
export class HomeComponent {
  defaultData : any = {
    firstName : "Roy",
    emailAddress : "[email protected]",
    phoneNumber : "+919895590754"
  }
  profileForm :FormGroup= new FormGroup({});

  get f() { return this.profileForm.controls; }

  constructor(private _formBuilder: FormBuilder){}
  ngOnInit(): void {
    this.profileForm =  this._formBuilder.group({
      firstName: ['',Validators.required],
      emailAddress: ['', Validators.required],
      phoneNumber: ['', Validators.required]
    })
    this.profileForm.setValue({firstName : this.defaultData.firstName ,emailAddress : this.defaultData.emailAddress, phoneNumber : this.defaultData.phoneNumber})
  }
    onSubmit() {
    try{
      if(this.profileForm.valid){
        alert('Profile form is valid');
      } else {
        alert('Profile form invalid');
      }
    } catch(error){
    }
  }
}


Unit Testing Required Field Validation


Let’s start by adding the `it` block.

  it('should fire required field validation for first name', () => {
    
  })


For the validation to fire the `firstName` field should have an empty value. So, let’s use the `defaultData` to set empty values in the form.

  it('should fire required field validation for first name', () => {
    component.defaultData = {
      firstName : "",
      emailAddress : "[email protected]",
      phoneNumber : "+919895590754"
    }
    fixture.detectChanges();
  })


Now for the validation to fire we need to submit the button by calling the button click handler.

  it('should fire required field validation for first name', () => {
    component.defaultData = {
      firstName : "",
      emailAddress : "[email protected]",
      phoneNumber : "+919895590754"
    }
    fixture.detectChanges();
    component.onSubmit();
  })


When the button is clicked since the first name field is empty the profile form required field validation should fire. We can validate the required field validation using the same. 

component.profileForm.get('firstName')?.errors?.['required']

Here is what the complete test case looks like:

  it('should fire required field validation for first name', () => {
    component.defaultData = {
      firstName : "",
      emailAddress : "[email protected]",
      phoneNumber : "+919895590754"
    }
    fixture.detectChanges();
    component.onSubmit();
    expect(component.profileForm.get('firstName')?.errors?.['required']).toEqual(true);
  })


Similarly, you can write a unit test case for validating the required validation.

For validating email and phone number required validation set the default value as empty for the respective field.

typescript
  it('should fire required field validation for email', () => {
    component.defaultData = {
      firstName : "hello",
      emailAddress : "",
      phoneNumber : "+919895590754"
    }
    fixture.detectChanges();
    component.onSubmit();
    expect(component.profileForm.get('emailAddress')?.errors?.['required']).toEqual(true);
  })

  it('should fire required field validation for phone number, () => {
    component.defaultData = {
      firstName : "hello",
      emailAddress : "[email protected]",
      phoneNumber : ""
    }
    fixture.detectChanges();
    component.onSubmit();
    expect(component.profileForm.get('phoneNumber')?.errors?.['required']).toEqual(true);
  })


Save the above changes and try running the unit tests.

bash
ng test


And the above should return success.

Unit Testing Button Submit


On click of the save button if the form is valid it shows an alert with the message `Profile form is valid` and if the form is invalid message is `Profile form invalid`. Here is the button click handler,

typescript
  onSubmit() {
    try{
      if(this.profileForm.valid){
        alert('Profile form is valid');
      } else {
        alert('Profile form invalid');
      }
    } catch(error){
    }
  }

In the above code, we can write unit tests for two scenarios, one when the profile form is valid and once when it’s invalid.

Let’s first write a valid form. Here is the `it` block,

typescript
  it('should alert valid form', () => {
    
  })


Since we are testing valid forms it will happen only when the form has all the required field values. Let’s set it using the `defaultData`.

typescript
  it('should alert valid form', () => {
    component.defaultData = {
      firstName : "hello",
      emailAddress : "[email protected]",
      phoneNumber : "+919895590754"
    }
    fixture.detectChanges();
  })


Now before submitting the button, we need to add a `spyOn` to check if the alert is getting fired or not. Jasmine provides us with a method called `spyOn` which we can use to monitor method calls. We’ll be using `spyOn` to check if an alert is being called with our expected message.

typescript
  it('should alert valid form', () => {
    component.defaultData = {
      firstName : "hello",
      emailAddress : "[email protected]",
      phoneNumber : "+919895590754"
    }
    fixture.detectChanges();
    spyOn(window, "alert");
    component.onSubmit();
    expect(window.alert).toHaveBeenCalledWith("Profile form is valid")
  })


We added the `spyOn` before the submit button call. Now once the button is submitted we check if the alert was called with the expected message or not.

Similarly, for invalid forms, you need to set an empty value for `defaultData` and check for an alert to show an invalid form message.

typescript
  it('should alert invalid form', () => {
    component.defaultData = {
      firstName : "",
      emailAddress : "[email protected]",
      phoneNumber : "+919895590754"
    }
    fixture.detectChanges();
    spyOn(window, "alert");
    component.onSubmit();
    
    expect(window.alert).toHaveBeenCalledWith("Profile form invalid")
  })


Save the changes made and run the test cases.

Wrapping it up


In this Angular unit testing tutorial, we explored how to write unit test cases for Angular form code. A form can have many more features and as the form grows unit test case writing becomes a necessary tool to validate the correctness of code.