Home > Web Front-end > JS Tutorial > body text

Automated Javascript testing with Mocha.js

WBOY
Release: 2023-09-14 10:41:02
forward
1276 people have browsed it

使用 Mocha.js 进行自动化 Javascript 测试

As we all know, code is prone to errors, and sometimes even if we know that a specific workflow will work fine in some cases, we are more likely to forget about others.

In simple terms, it can be said that when we test the code manually, we may miss something. For example, let's say we have two functions, func1() and func2(), and we know that func1() works for the following cases we're already testing is defined, but we find that func2() does not work. Then we fixed func2() but then forgot to check if func1() applied to the entire process after we made the change in func2(). This process can lead to errors, and this will typically happen several times.

Now, we know that running tests manually is not a very ideal option, so it is recommended to run separately written tests in addition to the code we may have written. This is the so-called automated testing.

In this tutorial, we will explore how to use Mocha for automated testing in JavaScript.

The first step is to be able to use Mocha simultaneously in our code. To do this, we can take advantage of the CDN link that mocha.js provides us. In this tutorial we will also use Chai.js and Expect.js which work well with when we want to check the exact behavior of our possible different functions Used with Mocha. Written.

Here are all the CDNs you need to import in your index.html file.

Expect.js

https://cdn.rawgit.com/Automattic/expect.js/0.3.1/index.js
Copy after login

Chai.js

https://cdn.rawgit.com/chaijs/chai/3.5.0/chai.js
Copy after login

Mocha.js

https://cdn.rawgit.com/mochajs/mocha/2.2.5/mocha.js
Copy after login

The next step is to create three files in the simple project directory of your favorite IDE or code editor.

  • index.html
  • index.js
  • test.js

You can also use the command shown below.

touch index.html index.js tests.js
Copy after login

Note - The touch command may not run on your local machine, in which case please use the vi command instead.

index.html

Now that we have created all the files, it's time to write the code. Open the index.html file and paste the following lines.

Example

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8">
   <title>Automated Testing With Mocha</title>
   <link href="https://cdn.rawgit.com/mochajs/mocha/2.2.5/mocha.css" rel="stylesheet" />
</head>
<body>
   <div id="mocha"></div>
   <script src="https://cdn.rawgit.com/Automattic/expect.js/0.3.1/index.js"></script>
   <script src="https://cdn.rawgit.com/chaijs/chai/3.5.0/chai.js"></script>
   <script src="https://cdn.rawgit.com/mochajs/mocha/2.2.5/mocha.js"></script>
   <script src="index.js"></script>
   <script>
      const mocha = window.mocha;
      mocha.setup('bdd');
   </script>
   <script src="tests.js"></script>
   <script>
      mocha.checkLeaks();
      mocha.run();
   </script>
</body>
</html>
Copy after login

illustrate

In the above HTML code, I imported all the dependencies via CDN such as Mocha, Chai and Expect.

Then I imported two different js files in synchronous order, namely index.js and tests.js, which means, first# The ##index.js file runs, followed by a script where I set window.mocha() and bdd.

Consider the code snippet shown below.

const mocha = window.mocha;
mocha.setup('bdd');
Copy after login

After the above code, I call the

tests.js file and then call different methods of Mocha. Consider the code snippet shown below.

mocha.checkLeaks();
mocha.run();
Copy after login

Now it's time for us to write some functions to test them in an automated way using Mocha. Consider the

index.js code shown below.

function addNumbers(a, b) {
   return a + b;
}
Copy after login

The function above is a very simple function where we take two parameters and then simply return the sum of those two numbers in the response.

test.js

Now comes the interesting part, we will test whether the above functionality works as expected with the help of automated tests. Consider the tests.js code shown below.

const chai = window.chai
const expect = chai.expect
describe('addNumbers', () => {
   it('should be able to add two numbers and give proper result', () => {
      expect(addNumbers(1, 3)).to.deep.equal(4)
      expect(addNumbers(1, 5)).to.deep.equal(6)
      expect(addNumbers(-9, -10)).to.deep.equal(-19)
   })
})
Copy after login

In the above code, I imported the

Chai and Expect packages through the index.html file. < 中存在的 CDN 链接提供给我们的。 /b>

Additionally, we are using the

describe function where the first parameter we pass is a string of our choice. Next, we create an anonymous function in which we call the it() function, which in turn takes a string as the first parameter and an anonymous arrow function as the second parameter.

We are using the

expect function where we call the actual function we want to test as a parameter and then check for equality using the deep.equal() method.

Output

After running the HTML code and opening the code in a browser, everything should work as expected. You should see text printed in your browser, somewhat similar to what is shown below.

>addNumbers
should be able to add two numbers and give proper result
Copy after login

Let’s add a second function

In the example above, we tested a simple JavaScript function called

addNumbers. Now, let's try adding another function, but this time, we'll use an arrow function. Consider the code shown below.

index.js

let multiplyNumber = (a, b) => {
   return a * b;
}
Copy after login
Copy after login

test.js

Now, let’s write an automated test for the above function in the

tests.js file. Consider the code snippet shown below.

describe('multiplyNumber', () => {
   it('should be able to multiply two numbers and give proper result',() => {
       expect(multiplyNumber(1, 3)).to.deep.equal(3)
      expect(multiplyNumber(1, 5)).to.deep.equal(5)
      expect(multiplyNumber(-9, -10)).to.deep.equal(90)
   })
})
Copy after login

Output

Run the HTML code and this time you will get the names of the two functions in the browser.

addNumbers
should be able to add two numbers and give proper result‣
multiplyNumber
should be able to multiply two numbers and give proper result
Copy after login

What if the function does not return the expected output?

In the two functions for which we wrote automated tests, we actually expected to get the correct values. What if we change the core logic of the function to return an error value?

考虑 index.js 文件中存在一个名为 multiplyNumber 的函数。让我们对函数进行更改,以便它不会给出我们预期的输出。

乘数

let multiplyNumber = (a, b) => {
   return a * b;
}
Copy after login
Copy after login

输出

现在,如果我们在浏览器中运行 HTML 代码,我们将在浏览器中得到以下输出。

multiplyNumber
should be able to multiply two numbers and give proper result‣
AssertionError: expected 0.3333333333333333 to deeply equal 3
Copy after login

使用多个描述函数进行自动化测试

在上面的两个示例中,我们使用了单个 describe 函数和简单函数。现在假设我们想要使用一个函数来计算数字的幂。

考虑下面所示的index.js代码

function power(x, n) {
   let res = 1;
   for (let i = 0; i < n; i++) {
      res *= x;
   }
   return res;
} 
Copy after login

在上面的函数中,我们采用两个参数,然后将一个数字的幂提高到 n 倍。

测试.js

现在让我们为此函数编写一个自动化测试。

describe("power", function () {
   describe("raises x to power 2", function () {
      function checkPower(x) {
         let expected = x * x;
         it(`${x} in the power 2 is ${expected}`, function () {
            expect(power(x, 2)).to.deep.equal(expected);
         });
      }
      for (let x = 1; x <= 5; x++) {
         checkPower(x);
      }
   });
});
Copy after login

我们可以看到,在自动化测试函数中,我们使用了嵌套的describe函数。在这里,我们检查在 index.js 中编写的 power() 函数是否按预期工作。

输出

power
raises x to power 2
1 in the power 2 is 1‣
2 in the power 2 is 4‣
3 in the power 2 is 9‣
4 in the power 2 is 16‣
5 in the power 2 is 25
Copy after login

结论

在本教程中,我们通过示例解释了如何使用 Mocha.js 与 Chai.js 和 Expect.js 在 JavaScript 中执行自动化测试。

The above is the detailed content of Automated Javascript testing with Mocha.js. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template