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
- toBeGreaterThan() is equivalent to
- >
- ==
- !=
- indexOf
- 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()
- !new RegExp().test()
not to indicate the judgment of negative values.
expect(true).not.toBe(false);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 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!

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr


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

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version
Chinese version, very easy to use

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools

Atom editor mac version download
The most popular open source editor
