preface

Because I often had to maintain some large business projects and some of my own open source projects, I started writing some single tests for better “canonical” code quality and iteration stability. The following is also mainly some of their own summary, due to the testing tools and frameworks many, here only introduces some browser end commonly used testing tools, the article if there is a problem also welcome to pat correct!! 🙂

Why test

In the past, when we were developing projects, we often neglected to write a single test, mostly because we didn’t have the time or wasted it. You also need to maintain test cases. In fact, projects tend to get more complex and larger over time, and if we change a common module that other people depend on, it may cause bugs in other people’s functionality. With automated testing, developers can trust their code more. Developers will no longer be afraid to hand over their code to someone else to maintain, and they won’t have to worry about other developers “breaking” their code. Later generations can take a piece of code with a test case and modify it more easily. The test cases clearly explain the expectations and requirements of developers and users for this end of the code, which is also very conducive to code inheritance.

Some of the concepts

TDD (Test Driven Development)

TDD stands for test-driven development, which simply means writing its tests before writing any functional code. Specific steps:

  • Write a test case as needed
  • Write functional code to make the test case pass
  • Step by step, add test cases
  • Modify the functional code to make the new test case pass as well as the original
  • Refactoring, including functional code and test cases

BDD(Behaviour Driven Development)

BDD is behavior-driven development, which can be understood as a branch of TDD, namely test-driven, but BDD emphasizes the writing style of tests, that is, tests should be written like natural language, using some assertions similar to natural language, such as Expect, should, so that each member of the project and even the product can understand the test. Even write tests.

Writing contrast

Whether it’s TDD or BDD, let’s compare some of them:

  // TDD
  suite('Array'.function() {
    setup(function() {}); test('equal -1 when index beyond array length'.function() {
      assert.equal(- 1[1.2.3].indexOf(4));
    });
  });

  // BDD
  describe('Array'.function() {
    before(function() {}); it('should return -1 when no such index'.function() {[1.2.3].indexOf(4).should.equal(- 1);
    });
  });
Copy the code

Simply put, writing in the BDD style is easier to understand and more semantic.

Assertions (assert)

During unit testing, development is expected to determine that certain logical conditions must be met when the program runs to a node so that the following business logic can proceed. If not, the program will “error” or even “crash”. Assertion is also used to determine the expectation that the result of a program execution should be a certain value.

Comparison of some assertion libraries

The assertion library provides a set of apis to help developers determine if a value meets expectations during unit testing, such as:

should.js
  value.should.equal(1);
  value.should.be.an.Object();
Copy the code
expect.js
expect(value).to.be(1)
expect(value).to.be.an('object')
Copy the code

chai

Chai is a BDD / TDD assertion library for node and the browser that can be delightfully paired with any javascript testing framework.

Chai provides three assertion styles to apply to BDD and TDD respectively. The Expect/Should API corresponds to the BDD style, and the Assert API corresponds to the TDD style.

The test framework

A “test framework” is a tool for running tests. It allows you to add tests to your JavaScript application to ensure the quality of your code.

Mocha

Mocha (pronounced “Mocha”), launched in 2011, is one of the most popular JavaScript testing frameworks available in both browsers and Node environments. For more information on the use and introduction of Mocha, see ruan’s test Framework MoCHA tutorial

Jasmine

Jasmine doesn’t rely on any framework, so it works with all Javascript code. A global function describe is used to describe each test and can be nested. The describe function takes two parameters, a string for description and a function for testing. Inside this function you can use the global function IT to define Specs, the main content of unit tests, and the expect function to test:

describe("A suite is just a function".function() {
  var a;
  it("and so is a spec".function() {
    a = true;
    expect(a).toBe(true);
  });
});
Copy the code

Front-end testing tool

Compared to server-side development, front-end development always faces a serious problem in testing, that is browser compatibility. Browser compatibility has always been an issue in front-end development, and I think even if browser compatibility is solved, device compatibility will be an issue in mobile development in the future.

The same is true for automated testing. Even if all the unit tests are concentrated in one runner, the front-end tests still have to deal with at least four browser kernels and three PC operating systems plus two or more mobile operating systems, not to mention the fragmentation of Android, which is a headache for mobile developers. But rest assured, tools already exist that can capture different browsers on different devices and keep them up to date with test results, or even see them all on a single terminal. Let’s focus on Karma

Karma

Karma is a JavaScript Test Runner based on Node.js. The tool can be used to test all major Web browsers, integrated into the Continuous Integration (CI) tool, or used with other code editors. A powerful feature of the test tool is that it can monitor changes to the Watch file and then perform them on its own, displaying test results through console.log.

The document

Istanbul

When testing, we often care about whether all code is tested. This metric is called code Coverage. It has four dimensions of measurement.

  • Line coverage: Is every line executed?
  • Function coverage: Is every function called?
  • Branch Coverage: Is every if block executed?
  • Statement coverage: Is every statement executed?

The app is named after Istanbul, Turkey’s largest city, because Turkish carpets are known around the world, and carpets are made to cover.

For detailed documentation refer to the Istanbul Tutorial, a code coverage tool by Prof Nguyen

Start work!

So let’s build an ES6 + Jasmine + Karma + Istanbul + Webpack basic test tool. Let’s start with a simple ES6 environment:

mkdir example

cd example

npm i babel-core bable-loader babel-preset-env --save
Copy the code

Then create the.babelrc file

{
    "presets": [
        "env"]}Copy the code

Next we need to install the Karma test tool:

$ npm install karma --save-dev

$ npm install karma-jasmine karma-chrome-launcher jasmine-core --save-dev
Copy the code

Next initialize karma:

karma init
Copy the code

This will add a file like karma. Conf.js to the directory. In order to use ES6 for testing, we need to use karma-webpack:

npm i webpack karma-webpack --save
Copy the code

Next, we do the familiar work of writing a webpack configuration file that loads the test script, such as webpack.test.js:

module.exports = {
  module: {
    rules: [{test: /\.js$/.exclude: /node_modules/.use: {
          loader: "babel-loader"}}]}};Copy the code

Rewrite our karma. Conf. js to introduce webpack:

const webpack = require('.. /webpack.config')

module.exports = function(config) {
  config.set({
    basePath: ' '.frameworks: ['jasmine'].files: [
      'test/**/*.spec.js'].exclude: [].preprocessors: {
      'test/add.spec.js': ['webpack']},webpack: webpack,
    reporters: ['progress'].port: 9876.colors: true.logLevel: config.LOG_INFO,
    autoWatch: true.browsers: ['Chrome'].singleRun: false.concurrency: Infinity})}Copy the code

Run Karma start.

Currently, our Reporters set progress, so only the final test results are shown, and the wrong statements are executed. If you want to see the results of each entry, you can install karma-spec-Reporter

npm install karma-spec-reporter --save-dev
Copy the code

Then add the spec to the reporters in karma. Conf.js:

reporters: ['spec']
Copy the code

This results in a formal report like this:

Second, we need to add Istanbul for code coverage testing. First we need to install a Babel plugin:

npm install babel-plugin-istanbul --save-dev 
Copy the code

Then modify our.babelrc file:

{
  // ...
  "env": {
    "test": {
      "presets": ["env"]."plugins": ["istanbul"]}}}Copy the code

By using the env attribute in.babelrc, when we set BABEL_ENV=test, we can execute plugins related to code tests, which is useful in test configuration in complex projects. Next, we need to install karma Istanbul for karma-coverage:

npm install karma karma-coverage --save-dev
Copy the code

Then let’s change the script inside package.json:

"scripts": {
    "test": "cross-env BABEL_ENV=test karma start test/karma.conf.js"
}
Copy the code

run

npm run test
Copy the code

Open the index.html file in coverage:

You can see some test results for coverage. But this is a little inconvenient, hope can directly output in the console is good. So we need to change the karma. Conf. js file and add a property like this:

coverageReporter: {
    dir: './coverage'.reporters: [{type: 'lcov'.subdir: '. ' },
        { type: 'text-summary' } // Output a summary on the console]}Copy the code

This allows us to print the basic coverage test results on the console:

At this point. A test environment has been built, which can meet the single test configuration of most projects.

conclusion

Maybe because people are more concerned about the business code at ordinary times, they will ignore some front-end testing work. The information on the Internet is also fragmentary, without a systematic summary and introduction. Here are some test tools to use, I hope you can help. Then all the code and original sources for this article are published on my personal blog. Also welcome to previous posts:

The blogs muwoo

Single test demo

Refer to the article

Test framework Mocha example tutorial

Code coverage tool Istanbul Tutorial

Node.js unit Tests: I write tests

Talk about unit testing for front-end development