Introduction to Angular unit testing using Jasmine
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.
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', () => { });
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); }) });
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 - !==
- !== undefined
- == = undefined
- === null
- !!obj
- !obj
- <
- >
- ==
- !=
- indexOf
- new RegExp( ).test()
- !new RegExp().test()
not to indicate the judgment of negative values.
expect(true).not.toBe(false);
Setup and Teardown
A general test code is very important, so we can put these repeated setup and teardown codes in The correspondingbeforeEach and
afterEach are in the global functions.
beforeEach means before each Spec is executed, and vice versa.
describe('demo test', () => { let val: number = 0; beforeEach(() => { val = 1; }); it('should be true', () => { expect(val).toBe(1); }); it('should be false', () => { expect(val).not.toBe(0); }); });
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.
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 onedescribe at this time would seem too elegant.
describe will make the test code and test report look more beautiful.
describe('AppComponent', () => { describe('Show User', () => { it('should be show panel.', () => {}); it('should be show avatar.', () => {}); }); describe('Hidden User', () => { it('should be hidden panel.', () => {}); }); });
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 thexdescribe and
xit global functions respectively to skip these test code blocks.
3. Cooperate with Angular tool set
Spy
Angular的自定义事件实在太普遍了,但为了测试这些自定义事件,因此监控事件是否正常被调用是非常重要。好在,Spy
可以用于监测函数是否被调用,这简直就是我们的好伙伴。
以下示例暂时无须理会,暂且体验一下:
describe('AppComponent', () => { let fixture: ComponentFixture<TestComponent>; let context: TestComponent; beforeEach(() => { TestBed.configureTestingModule({ declarations: [TestComponent] }); fixture = TestBed.createComponent(TestComponent); context = fixture.componentInstance; // 监听onSelected方法 spyOn(context, 'onSelected'); fixture.detectChanges(); }); it('should be called [selected] event.', () => { // 触发selected操作 // 断言是否被调用过 expect(context.onSelected).toHaveBeenCalled(); }); });
异步支持
首先,这里的异步是指带有 Observable 或 Promise 的异步行为,因此对于组件在调用某个 Service 来异步获取数据时的测试状态。
假设我们的待测试组件代码:
export class AppComponent { constructor(private _user: UserService) {} query() { this._user.quer().subscribe(() => {}); } }
async
async
无任何参数与返回值,所有包裹代码块里的测试代码,可以通过调用 whenStable()
让所有待处理异步行为都完成后再进行回调;最后,再进行断言操作。
it('should be get user list (async)', async(() => { // call component.query(); fixture.whenStable().then(() => { fixture.detectChanges(); expect(true).toBe(true); }); }));
fakeAsync
如果说 async
还需要回调才能进行断点让你受不了的话,那么 fakeAsync
可以解决这一点。
it('should be get user list (async)', fakeAsync(() => { // call component.query(); tick(); fixture.detectChanges(); expect(true).toBe(true); }));
这里只是将回调换成 tick()
,怎么样,是不是很酷。
Jasmine自带异步
如前面所说的异步是指带有 Observable 或 Promise 的异步行为,而有时候我们有些东西是依赖 setTimeout
或者可能是需要外部订阅结果以后才能触发时怎么办呢?
可以使用 done()
方法。
it('async demo', (done: () => void) => { context.show().subscribe(res => { expect(true).toBe(true); done(); }); el.querySelected('xxx').click(); });
四、结论
本章几乎所有的内容在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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











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.

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 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 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.

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

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

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.

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.
