Home Web Front-end JS Tutorial Introduction to Angular unit testing using Jasmine

Introduction to Angular unit testing using Jasmine

Aug 22, 2020 am 11:23 AM

This article will talk about how to use Jasmine for Angular unit testing? It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Introduction to Angular unit testing using Jasmine

The following is prepared by me assuming that those who have rarely or not written unit tests at all, therefore, can explain many conceptual issues in vernacular, and will also use Jasmine to respond to them. methods are explained.

1. Concept

Test Suite

Test Suite, Even a simple class will have several test cases, so the collection of these test cases under one category is called Test Suite.

In Jasmine, it is represented by the describe global function. Its first string parameter is used to represent the name or title of the Suite, and the second method parameter is to implement the Suite code. .

describe('test suite name', () => {
});
Copy after login

Specs

A Specs is equivalent to a test case, which is the specific body of code we implement to test.

Jasmine uses the it global function to represent it, similar to describe, with two parameters: string and method.

Each Spec includes multiple expectations to test the code that needs to be tested. As long as any expectation result is false, it means that the test case is in a failed state.

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

Expectations

Assertions are represented by expect global functions, only receiving one representative ## to be tested #Actual value, and needs to be matched with Matcher to represent expected value.

2. Common methods

Matchers

Assertion matching operations , compare the actual value with the expected value, and notify Jasmine of the result. Finally, Jasmine will determine whether this Spec succeeds or fails.

Jasmine provides a very rich API, some commonly used Matchers:

  • toBe() is equivalent to ===
  • toNotBe() is equivalent to
  • !==
  • toBeDefined() is equivalent to
  • !== undefined
  • toBeUndefined() is equivalent to
  • == = undefined
  • toBeNull() is equivalent to
  • === null
  • toBeTruthy() is equivalent to
  • !!obj
  • toBeFalsy() is equivalent to
  • !obj
  • toBeLessThan() is equivalent to
  • <
  • toBeGreaterThan() is equivalent to
  • >
  • toEqual() is equivalent to
  • ==
  • toNotEqual() is equivalent to
  • !=
  • toContain() is equivalent to
  • indexOf
  • toBeCloseTo() defines the precision when comparing numerical values, rounding first and then comparing.
  • toHaveBeenCalled() Checks whether the function has been called
  • toHaveBeenCalledWith() Checks whether the incoming parameters have been called as parameters
  • toMatch() is equivalent to
  • new RegExp( ).test()
  • toNotMatch() is equivalent to
  • !new RegExp().test()
  • toThrow() Check whether the function will throw an error
These APIs previously used

not to indicate the judgment of negative values.

expect(true).not.toBe(false);
Copy after login

These Matchers can almost meet our daily needs. Of course, you can also customize your own Matcher to meet special needs.

Setup and Teardown

A general test code is very important, so we can put these repeated setup and teardown codes in The corresponding

beforeEach and afterEach are in the global functions.

beforeEach means before each Spec is executed, and vice versa.

describe(&#39;demo test&#39;, () => {
    let val: number = 0;
    beforeEach(() => {
        val = 1;
    });
    it(&#39;should be true&#39;, () => {
        expect(val).toBe(1);
    });
    it(&#39;should be false&#39;, () => {
        expect(val).not.toBe(0);
    });
});
Copy after login

Data sharing

As in the above example, we can define it at the beginning of each test file,

describe Corresponding variables so that each it can share them internally.

Of course, each Spec execution cycle will also be accompanied by an empty

this object until it is cleared after the Spec execution is completed. You can also use this data sharing.

Nested code

Sometimes when we test a component, the component will have different states to display different As a result, using just one

describe at this time would seem too elegant.

Therefore, nesting

describe will make the test code and test report look more beautiful.

describe(&#39;AppComponent&#39;, () => {
    describe(&#39;Show User&#39;, () => {
        it(&#39;should be show panel.&#39;, () => {});
        it(&#39;should be show avatar.&#39;, () => {});
    });
    describe(&#39;Hidden User&#39;, () => { 
        it(&#39;should be hidden panel.&#39;, () => {});
    });
});
Copy after login

Skip the test code block

The demand is always half-hearted, but the test code that was finally written should be deleted? No...

Suites and Specs can use the

xdescribe and xit global functions respectively to skip these test code blocks.

3. Cooperate with Angular tool set

Spy

Angular的自定义事件实在太普遍了,但为了测试这些自定义事件,因此监控事件是否正常被调用是非常重要。好在,Spy 可以用于监测函数是否被调用,这简直就是我们的好伙伴。

以下示例暂时无须理会,暂且体验一下:

describe(&#39;AppComponent&#39;, () => {
    let fixture: ComponentFixture<TestComponent>;
    let context: TestComponent;

    beforeEach(() => {
        TestBed.configureTestingModule({
            declarations: [TestComponent]
        });
        fixture = TestBed.createComponent(TestComponent);
        context = fixture.componentInstance;
        // 监听onSelected方法
        spyOn(context, &#39;onSelected&#39;);
        fixture.detectChanges();
    });

    it(&#39;should be called [selected] event.&#39;, () => {
        // 触发selected操作

        // 断言是否被调用过
        expect(context.onSelected).toHaveBeenCalled();
    });
});
Copy after login

异步支持

首先,这里的异步是指带有 Observable 或 Promise 的异步行为,因此对于组件在调用某个 Service 来异步获取数据时的测试状态。

假设我们的待测试组件代码:

export class AppComponent {
  constructor(private _user: UserService) {}

  query() {
    this._user.quer().subscribe(() => {});
  }
}
Copy after login

async

async 无任何参数与返回值,所有包裹代码块里的测试代码,可以通过调用 whenStable()所有待处理异步行为都完成后再进行回调;最后,再进行断言操作。

it(&#39;should be get user list (async)&#39;, async(() => {
    // call component.query();
    fixture.whenStable().then(() => {
        fixture.detectChanges();
        expect(true).toBe(true);
    });
}));
Copy after login

fakeAsync

如果说 async 还需要回调才能进行断点让你受不了的话,那么 fakeAsync 可以解决这一点。

it(&#39;should be get user list (async)&#39;, fakeAsync(() => {
    // call component.query();
    tick();
    fixture.detectChanges();
    expect(true).toBe(true);
}));
Copy after login

这里只是将回调换成 tick(),怎么样,是不是很酷。

Jasmine自带异步

如前面所说的异步是指带有 Observable 或 Promise 的异步行为,而有时候我们有些东西是依赖 setTimeout 或者可能是需要外部订阅结果以后才能触发时怎么办呢?

可以使用 done() 方法。

it(&#39;async demo&#39;, (done: () => void) => {
    context.show().subscribe(res => {
        expect(true).toBe(true);
        done();
    });
    el.querySelected(&#39;xxx&#39;).click();
});
Copy after login

四、结论

本章几乎所有的内容在Angular单元测试经常使用到的东西;特别是异步部分,三种不同异步方式并非共存的,而是需要根据具体业务而采用。否则,你会发现真TM难写单元测试。毕竟这是一个异步的世界。

自此,我们算是为Angular写单元测试打下了基础。后续,将不会再对这类基础进行解释。

happy coding!

相关教程推荐:angular教程

The above is the detailed content of Introduction to Angular unit testing using Jasmine. 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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1246
24
The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript and the Web: Core Functionality and Use Cases JavaScript and the Web: Core Functionality and Use Cases Apr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

See all articles