Table of Contents
Configuration script
Home Web Front-end JS Tutorial How to set up a test environment? Introduction to Angular testing toolset

How to set up a test environment? Introduction to Angular testing toolset

Aug 22, 2020 am 11:16 AM
angular unit test

How to set up a test environment? Introduction to Angular testing toolset

This article will discuss how to build a test environment and the Angular testing tool set.

Test environment

Most of the projects are created using Angular Cli. Therefore, the npm packages we need have been integrated by default. Script; of course, if you use self-built or official website quickstart, you need to install it yourself; but all the core data are the same. [Related tutorial recommendations: angular tutorial]

We can divide Angular unit testing into two categories: independent individual testing and Angular testing toolset.

Pipe and Service are suitable for independent testing, because they only require new instance classes; they are also unable to interact with Angular components in any way.

The opposite is the Angular testing toolset.

Testing framework introduction

Jasmine

Jasmine testing framework provides tools for writing test scripts Set, and very good semantics, making the test code look like reading a paragraph.

Karma

There are test scripts, and Karma is needed to help manage these scripts so that they can be run in the browser.

Npm package

If you have to mess around, the easiest way is to create a new project through Angular Cli, and then add the following Copy the Npm package to the project you are working on.

    "jasmine-core": "~2.5.2",
    "jasmine-spec-reporter": "~3.2.0",
    "karma": "~1.4.1",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "karma-coverage-istanbul-reporter": "^0.2.0"
Copy after login

Then, the most important thing for us is to look at the configuration script part.

Configuration script

Our core is to let the karma runner run, and for Jasmine, it will be used when we write the test script, so for the time being No need to be overly concerned.

We need to create the karma.conf.js file in the root directory, which is equivalent to some conventions. The purpose of the file is to inform karma which plug-ins need to be enabled, which test scripts to load, which test browser environments are required, test report notification methods, logs, etc.

karma.conf.js

The following is the karma configuration file provided by Angular Cli by default:

// Karma configuration file, see link for more information
// https://karma-runner.github.io/0.13/config/configuration-file.html

module.exports = function(config) {
    config.set({
        // 基础路径(适用file、exclude属性)
        basePath: '',
        // 测试框架,@angular/cli 指Angular测试工具集
        frameworks: ['jasmine', '@angular/cli'],
        // 加载插件清单
        plugins: [
            require('karma-jasmine'),
            require('karma-chrome-launcher'),
            require('karma-jasmine-html-reporter'),
            require('karma-coverage-istanbul-reporter'),
            require('@angular/cli/plugins/karma')
        ],
        client: {
            // 当测试运行完成后是否清除上文
            clearContext: false // leave Jasmine Spec Runner output visible in browser
        },
        // 哪些文件需要被浏览器加载,后面会专门介绍  `test.ts`
        files: [
            { pattern: './src/test.ts', watched: false }
        ],
        // 允许文件到达浏览器之前进行一些预处理操作
        // 非常丰富的预处理器:https://www.npmjs.com/browse/keyword/karma-preprocessor
        preprocessors: {
            './src/test.ts': ['@angular/cli']
        },
        // 指定请求文件MIME类型
        mime: {
            'text/x-typescript': ['ts', 'tsx']
        },
        // 插件【karma-coverage-istanbul-reporter】的配置项
        coverageIstanbulReporter: {
            // 覆盖率报告方式
            reports: ['html', 'lcovonly'],
            fixWebpackSourcePaths: true
        },
        // 指定angular cli环境
        angularCli: {
            environment: 'dev'
        },
        // 测试结果报告方式
        reporters: config.angularCli && config.angularCli.codeCoverage ?
            ['progress', 'coverage-istanbul'] :
            ['progress', 'kjhtml'],
        port: 9876,
        colors: true,
        // 日志等级
        logLevel: config.LOG_INFO,
        // 是否监听测试文件
        autoWatch: true,
        // 测试浏览器列表
        browsers: ['Chrome'],
        // 持续集成模式,true:表示浏览器执行测试后退出
        singleRun: false
    });
};
Copy after login

The above configuration can basically meet our needs ; Generally, what needs to be changed is the test browser list, because karma supports all browsers on the market. In addition, when you use Travis CI continuous integration, starting a disable sandbox environment Chrome browser will save us a lot of things:

        customLaunchers: {
            Chrome_travis_ci: {
                base: 'Chrome',
                flags: ['--no-sandbox']
            }
        }
Copy after login

For all information about karma config files, please participate inOfficial website documentation .

test.ts

When writing karma.conf.js, we configured the file loaded by the browser to point to ./src/test.ts file. The function is to guide karma to start, and the code is much simpler:

// This file is required by karma.conf.js and loads recursively all the .spec and framework files

import 'zone.js/dist/long-stack-trace-zone';
import 'zone.js/dist/proxy.js';
import 'zone.js/dist/sync-test';
import 'zone.js/dist/jasmine-patch';
import 'zone.js/dist/async-test';
import 'zone.js/dist/fake-async-test';
import { getTestBed } from '@angular/core/testing';
import {
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';

// Unfortunately there's no typing for the `__karma__` variable. Just declare it as any.
declare var __karma__: any;
declare var require: any;

// Prevent Karma from running prematurely.
__karma__.loaded = function () {};

// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting()
);
// Then we find all the tests.
// 所有.spec.ts文件
const context = require.context('./', true, /\.spec\.ts$/);
// And load the modules.
context.keys().map(context);
// Finally, start Karma to run the tests.
__karma__.start();
Copy after login

After everything is ready, we can try to start karma. It can run even without any test code.

If it is Angular Cli then ng test. Tossing withnode "./node_modules/karma-cli/bin/karma" start

Finally, open the browser: http://localhost :9876, you can view the test report.

Simple example

Now that the environment is set up, let’s write a simple example to try.

Create ./src/demo.spec.ts file. The suffix .spec.ts is a convention, follow it.

describe('demo test', () => {
    it('should be true', () => {
        expect(true).toBe(true);
    })
});
Copy after login

After running ng test, we can see in the console:

Chrome 58.0.3029 (Windows 10 0.0.0): Executed 1 of 1 SUCCESS (0.031 secs / 0.002 secs)
Copy after login

or browser:

1 spec, 0 failures
demo test
  true is true
Copy after login

No matter what , after all, we have entered the world of Angular unit testing.

Angular Testing Toolset

Ordinary classes such as Pipe or Service only need to create instances through a simple new. For instructions and components, a certain environment is required. This is because of Angular's module concept. If you want a component to run, you must first have a @NgModule definition.

The tool set does not contain a lot of information, and you can easily master it. Below I will briefly explain a few of the most commonly used ones:

TestBed

TestBed is provided by the Angular testing tool set for building a @NgModule Test environment module. Of course, with the module, you also need to use TestBed.createComponent to create a test component for testing the target component.

Asynchronous

Asynchronous is everywhere in Angular, and asynchronous testing can use the toolset async, fakeAsync to write elegant tests The code looks synchronous.

There are more tools in the tool set, all of which we will explain one by one in [Angular Unit Testing - Component and Instruction Unit Testing]().

happy coding!

The above is the detailed content of How to set up a test environment? Introduction to Angular testing toolset. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Unit testing practices for interfaces and abstract classes in Java Unit testing practices for interfaces and abstract classes in Java May 02, 2024 am 10:39 AM

Steps for unit testing interfaces and abstract classes in Java: Create a test class for the interface. Create a mock class to implement the interface methods. Use the Mockito library to mock interface methods and write test methods. Abstract class creates a test class. Create a subclass of an abstract class. Write test methods to test the correctness of abstract classes.

The difference between performance testing and unit testing in Go language The difference between performance testing and unit testing in Go language May 08, 2024 pm 03:09 PM

Performance tests evaluate an application's performance under different loads, while unit tests verify the correctness of a single unit of code. Performance testing focuses on measuring response time and throughput, while unit testing focuses on function output and code coverage. Performance tests simulate real-world environments with high load and concurrency, while unit tests run under low load and serial conditions. The goal of performance testing is to identify performance bottlenecks and optimize the application, while the goal of unit testing is to ensure code correctness and robustness.

Analysis of the advantages and disadvantages of PHP unit testing tools Analysis of the advantages and disadvantages of PHP unit testing tools May 06, 2024 pm 10:51 PM

PHP unit testing tool analysis: PHPUnit: suitable for large projects, provides comprehensive functionality and is easy to install, but may be verbose and slow. PHPUnitWrapper: suitable for small projects, easy to use, optimized for Lumen/Laravel, but has limited functionality, does not provide code coverage analysis, and has limited community support.

How to use table-driven testing method in Golang unit testing? How to use table-driven testing method in Golang unit testing? Jun 01, 2024 am 09:48 AM

Table-driven testing simplifies test case writing in Go unit testing by defining inputs and expected outputs through tables. The syntax includes: 1. Define a slice containing the test case structure; 2. Loop through the slice and compare the results with the expected output. In the actual case, a table-driven test was performed on the function of converting string to uppercase, and gotest was used to run the test and the passing result was printed.

What is the difference between unit testing and integration testing in golang function testing? What is the difference between unit testing and integration testing in golang function testing? Apr 27, 2024 am 08:30 AM

Unit testing and integration testing are two different types of Go function testing, used to verify the interaction and integration of a single function or multiple functions respectively. Unit tests only test the basic functionality of a specific function, while integration tests test the interaction between multiple functions and integration with other parts of the application.

PHP Unit Testing: How to Design Effective Test Cases PHP Unit Testing: How to Design Effective Test Cases Jun 03, 2024 pm 03:34 PM

It is crucial to design effective unit test cases, adhering to the following principles: atomic, concise, repeatable and unambiguous. The steps include: determining the code to be tested, identifying test scenarios, creating assertions, and writing test methods. The practical case demonstrates the creation of test cases for the max() function, emphasizing the importance of specific test scenarios and assertions. By following these principles and steps, you can improve code quality and stability.

PHP Unit Testing: Tips for Increasing Code Coverage PHP Unit Testing: Tips for Increasing Code Coverage Jun 01, 2024 pm 06:39 PM

How to improve code coverage in PHP unit testing: Use PHPUnit's --coverage-html option to generate a coverage report. Use the setAccessible method to override private methods and properties. Use assertions to override Boolean conditions. Gain additional code coverage insights with code review tools.

Integration of PHP unit testing and continuous delivery Integration of PHP unit testing and continuous delivery May 06, 2024 pm 06:45 PM

Summary: By integrating the PHPUnit unit testing framework and CI/CD pipeline, you can improve PHP code quality and accelerate software delivery. PHPUnit allows the creation of test cases to verify component functionality, and CI/CD tools such as GitLabCI and GitHubActions can automatically run these tests. Example: Validate the authentication controller with test cases to ensure the login functionality works as expected.

See all articles