EP01: Jest, Npm, Shell.js
10 Minutes Read / 3 Topics
We have 3 topics in this episode, which takes about 10 minutes to read!
How to Mock a React Component in Jest
NPM Package Lifecycle Events
Trigger Shell Commands using Shell.js
01. How to Mock a React Component in Jest
Mocking a React component in Jest involves creating a fake version of the component for testing purposes. This is useful when you want to isolate the component's behavior from other components or when you want to test a component that relies on other components or modules.
Let’s try to test the handleLoginExpired function when the user login status got expired
Cause we can’t control the internal onLoginExpired trigger logic, the handleLoginExpired might be a dead zone during testing.
Here we use jest.mock function to create a mock version of the PaymentModule component.
The jest.mock function takes two arguments:
Path: path to the module you want to mock (in this case,
Mock Body: a function that returns a new version of the module.
Mock the Component
In this case, we are returning a new module implementation which will trigger the onLoginExpired callback immediately when the module is rendered.
02. NPM Package Lifecycle Events
NPM (Node Package Manager) has a set of lifecycle events that are triggered at specific points during the installation and use of an NPM package. These events are specified in the package.json file of the package and are executed in a predefined order.
Here is a list of the NPM package lifecycle events, in the order they are executed:
preinstall: This event is triggered before the package is installed.
install: This event is triggered during the package installation process.
postinstall: This event is triggered after the package is installed.
preuninstall: This event is triggered before the package is uninstalled.
uninstall: This event is triggered during the package uninstallation process.
postuninstall: This event is triggered after the package is uninstalled.
prepublish: This event is triggered before the package is published.
publish: This event is triggered when the package is published.
postpublish: This event is triggered after the package is published.
In addition to these events, there are also some less commonly used events, such as:
pretest, test, posttest,
prestart, start, poststart
prestop, stop, poststop
which are used for specific purposes in the package development and deployment process.
03. Trigger Shell Commands using Shell.js
Shell.js is a Node.js library that provides a simple and consistent API for running shell commands on different operating systems. Here's an example of how to use Shell.js to trigger shell commands:
Additionally, Shell.js provides several other functions for running shell commands.
For more information on how to use Shell.js, you can refer to its official documentation.