angular tutorial

"/> angular tutorial

">

Home  >  Article  >  Web Front-end  >  Introduction to Angular unit testing using Jasmine

Introduction to Angular unit testing using Jasmine

青灯夜游
青灯夜游forward
2020-08-22 11:23:262698browse

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', () => {
});

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
  • !==
  • 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
  • 4cb2d32f466e76ace041ece7f8676abf
  • 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);

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

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('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 the

xdescribe 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, &#39;onSelected&#39;);
        fixture.detectChanges();
    });

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

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

异步支持

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

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

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

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

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);
    });
}));

fakeAsync

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

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

这里只是将回调换成 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();
});

四、结论

本章几乎所有的内容在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:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete