PHPUnit is an automated testing framework for PHP and Magento 2 supports it out of the box with PHPUnit. As a good software engineer, one must consider writing their code by following the Test Driven Development a.k.a. TDD approach so in this quick tutorial, I will briefly explain the idea of PHP Unit Testing and why is important to follow TDD.
What is Unit Testing?
Unit Testing simply refers to testing every individual component/unit of a software. The objective is to ensure and validate that each unit of the software you are writing performs as designed. A unit is the smallest testable part of your application that usually accepts one or a few inputs and mostly a single output. One of the benefits of Unit testing is that this process is fully automated and does not require man hours to review and test the code.
Why Unit Test?
There are several benefits of Unit Testing but the key three benefits are as follow:
Early problem detection
Have you just created a beautiful software but one or more sections do not work in production? If yes then welcome to Unit Testing using which we can find the problems early in the development cycle.
Facilitates Change
Is there a new version of the programming language available and the version in which you wrote your software been deprecated? No problem – Unit testing allows you to refactor code or upgrade system libraries at a later date, and make sure the module still works correctly. The idea of unit testing is to write test cases for all functions so if a change causes a fault, it can be quickly identified.
Design
Ok I am not talking about your website frontend design or the flashy colours here. I’m instead referring to Design Patterns of your software. Unit Tests are to be written prior to the implementation of the actual code, and this approach helps a developer to think through the design and the end goal before the development begins.
Enough of the theory .. now let’s move on and create a simple Unit Test for your Bespoke Magento Module.
Write a unit test in Magento 2
Let’s assume that you have created a simple Magento 2 module called Shoman_MyFirstModule; that has its configuration area in Store > Configuration (say Shoman > My First Module), and in the configuration area you have a dropdown with Yes/No value.
Your module has a Helper Class called Data.php with a method called isEnabled(). The content of the file is as follows:
As you can see in the code above, we have simple function that pulls and returns the value of the custom configuration.
Next, we are going to create a Unit Test for this Helper Class.
In your custom module root, create a new directory Test/Unit/Helper; and since your Helper class is called Data.php so create a new file called DataTest.php in the path app/code/Shoman/MyFirstModule/Test/Unit/Helper. Your directory structure will look like the one in the image below:
DataTest.php will extend \PHPUnit\Framework\TestCase and have two functions:
setUp() – treat it as a __construct() function
testIsEnabled() – isEnabled() is the original function in the Data.php class. We have prefixed the original function name with test so we can run a Unit Test on it.
Earlier this week, Adobe identified RCE vulnerability in both commerce and open source editions and released a security patch APSB22-12 marked as Critical Priority to be installed immediately.
What this means is if you are running your website on Adobe Commerce (2.3.3-p1-2.3.7-p2) or Magento Open Source (2.4.0-2.4.3-p1), then your website is at high risk and needs to be patched immediately.
Once you have downloaded the appropriate patches, you can create a new directory called i.e. ./patches in your Magento root, upload patch files and run the following commands:
There are many times when you would want to add a custom <script> just before the opening head tag in Magento but no matter what you do, the script will always get added after Magento loads its requireJS which isn’t much helpful, but in this article, I will share the steps you can take to ensure that your script gets added right after the opening <head> tag – yes, even before Magento injects its requireJS.
By default Magento 2 uses the root.phtml file to setup head content accordingly, which is located in vendor/magento/module-theme/view/base/templates/root.phtml (unless it has been overridden in your custom theme). The content of the root.phtml is as follows:
This file contains the $requireJs variable and block and the require.js block is defined in vendor/Magento/module-theme/view/frontend/layout/default.xml content of which is as follows:
Now, there are two possible solutions to override the file:
By overriding the file in your custom theme
By creating a simple module (preferred)
Override require_js.phtml in your custom theme
To override the the file in your custom theme, copy require_js.phtml from vendor/magento/module-theme/view/frontend/templates/page/js to your theme app/design/frontend/{VENDOR}/{THEME_NAME}/Magento_Theme/templates/page/js/ and finally, put your custom JS code just above the requireJS block i.e.
As you can see, in the code above, we are setting a new template file code.phtml for the require.js block.
Next, go ahead and create the code.phtml file in ./view/frontend/templates and add the custom code as follows:
<?php
<!-- My Custom Script start -->
<script type="text/javascript">
console.log("Hello World!");
</script>
<!-- My Custom Script end -->
<script>
var BASE_URL = '<?= $block->escapeUrl($block->getBaseUrl()) ?>';
var require = {
"baseUrl": "<?= /* @escapeNotVerified */ $block->getViewFileUrl('/') ?>"
};
</script>
I have created a simple module that does the job already and you can download it from here: https://github.com/shoaibrehman/Magento2-OneTrust-Cookies – this module primarily focus on integrating OneTrust Cookie Policy script so feel free to replace the content of code.phtml file as per your needs or you can fork the module and modify it as per your needs!
OneTrust is one of the popular user consent management systems out in the market which allows business to monitor Privacy, Security & Data Governance in their platform.
While it has integrations with many popular web platforms, it is missing a solid integration with Magento.
It’s a simple tracking script which one would easily copy/paste in Magento admin > Content > Design > Themes > Head > Misc script; but the catch is that this script needs to be put right after the opening <head> tag which is not possible if you copy/paste the script in Magento backend theme configuration area.
To achieve this, I have created a simple Magento module (compatible with 2.2.x, 2.3.x, 2.4.x) using which you can put the OneTrust Cookie Script in the right location.
Once the image is installed, you will need to go to https://127.0.0.1:8443/ as that’s where the docker image is installed.
Next, click on the Add Domain button to add a new local domain to install your Magento:
Important: Magento has removed the root index.php in Magento 2.4.2 and moved it to the ./pub directory so you will need to add ./pub to your document root as shown in the image above.
Once the domain is setup, you will need to create a database which you can create by clicking on the Databases link from the left hand menu.
Next, it is now time to download Magento on your local server but first you will need to login to the MGT Commerce’s Docker Image.
Open terminal and ssh using the following details:
FTP HOST:127.0.0.1:22
USERNAME: root
PASSWORD: root
.. then navigate to the htdocs directory i.e.cd htdocs/playground.magento.com/
Finally, run the following to download Magento to the site root:
Once the installation is complete, you should be able to access Magento on https://playground.magento.com/ (but remember you will need to add this entry in your hosts file to access the site).
I am a Magento certified expert with a 100% success rate on UpWork (View Profile) and more than 2000 hrs.
I am an eCommerce Enthusiast and started using Magento back in 2014. I specialise in creating custom and bespoke modules for Magento including but not limited to third party integrations and bespoke business requirements.