So let's continue our last discussion regarding automation testing and today I’ll show you examples of automation testing. Let’s begging by covering what you need to start testing. Remember we are going to test in Javascript code.
TESTING SETUP:
Test Runner:
We will need a test runner to execute your tests and summarize your test results. Example: Mocha
Assertion library:
Here we define our testing logic and conditions. This is where we define expectations. Example: Chai
For this example, I’m going to use JEST and this will be my test runner and my assertion library in one place. Today we are going over only unit testing.
If you wish to learn more about JEST JS here is the link for the docs: https://jestjs.io/
Installing JEST:
yarn add --dev jest
or with NPM:
npm install --save-dev jest
Note: Jest documentation uses yarn
commands, but npm
will also work. You can compare yarn
and npm
commands in the yarn docs, here.
Let’s get started by writing a test for a hypothetical function that returns the name and age of a person giving the input. this function will take two arguments: name and age. First, let's create the generator.js file:
exports.generatetext = (name, age) =>{// return output textreturn `${name} (${age} years old)`};
Then, create a file named generator.test.js
. This will contain our actual test and JEST will automatically look for files with the .test.js on their name. First, we need to import the file we are going to test relative to the position of our .test.js file and this is our first line of code.
const { generatetext} = require('./generator');test('should output a name and age', () =>{const text = generatetext('Max', 29);expect(text).toBe('Max (29 years old)')});
in this example, we are expecting the result for this text to be “Max (29 years old)” if we receive anything other than that this test will fail.
Make sure to add the following section to your package.json
:
{"scripts": {"test": "jest"}}
Finally, run yarn jest
or npm run jest
and Jest will print this message:
PASS cypress/integration/util.spec.js
PASS src/util.test.jsTest Suites: 2 passed, 2 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 2.486 s, estimated 3 s
Ran all test suites.
Done in 5.69s.
Now our test is passing.