[Angular Unit Testing] Testing Component with ChangeDetectionStrategy.OnPush

Component:

<div class="loading-placeholder" [ngClass]="extraClass">
    &nbsp;
    <ng-container *ngIf="loadingService.config.showContent">
        <ng-content></ng-content>
    </ng-container>
</div>
复制代码
import {Component, OnInit, Input, ChangeDetectionStrategy} from '@angular/core'
import {LoadingService} from '../loading.service'

@Component({
    selector: 'loading-placeholder',
    templateUrl: './loading-placeholder.component.html',
    styleUrls: ['./loading-placeholder.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class LoadingPlaceholderComponent implements OnInit {
    @Input() type: string
    @Input() size: string

    extraClass: string

    constructor(public loadingService: LoadingService) {}

    ngOnInit(): void {
        this.extraClass = this.getType()
    }

    getType() {
        const whiteList = ['image', 'headline', 'text']
        const sizes = ['small', 'medium', 'large', 'full']
        const alias = ['s', 'm', 'l', 'f']
        let res = ''

        if (whiteList.indexOf(this.type) === -1) {
            return res
        }

        if (
            sizes.indexOf(this.size) === -1 &&
            alias.indexOf(this.size) === -1
        ) {
            return `loading-placeholder__${this.type}`
        }

        return `loading-placeholder__${this.type}--${this.size}`
    }
}
复制代码

 

Testing:

复制代码
import {
    async,
    ComponentFixture,
    TestBed,
    fakeAsync,
    flush
} from '@angular/core/testing'

import {LoadingPlaceholderComponent} from './loading-placeholder.component'
import {LoadingService} from '../loading.service'
import {of} from 'rxjs'
import {DebugElement, Component, ChangeDetectionStrategy} from '@angular/core'
import {By} from '@angular/platform-browser'

fdescribe('LoadingPlaceholderComponent', () => {
    let component: LoadingPlaceholderComponent
    let fixture: ComponentFixture<LoadingPlaceholderComponent>
    let el: DebugElement
    let loadingService: LoadingService
    let loadingServiceSpy = {
        loading$: of(true),
        get config() {
            return {showContent: false}
        }
    }

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [LoadingPlaceholderComponent],
            providers: [{provide: LoadingService, useValue: loadingServiceSpy}]
        })
            .overrideComponent(LoadingPlaceholderComponent, {
                set: new Component({
                    templateUrl: './loading-placeholder.component.html',
                    changeDetection: ChangeDetectionStrategy.Default
                })
            })
            .compileComponents()
    }))

    beforeEach(() => {
        fixture = TestBed.createComponent(LoadingPlaceholderComponent)
        component = fixture.componentInstance
        el = fixture.debugElement
        loadingService = TestBed.inject(LoadingService)
        fixture.detectChanges()
    })


        it('should has correct className', () => {
            component.size = 'm'
            component.type = 'headline'
            component.ngOnInit()
            fixture.detectChanges()
            expect(component.extraClass).toBe(
                'loading-placeholder__headline--m',
                'extraClass has wrong value'
            )

            expect(
                el.query(By.css('.loading-placeholder')).nativeElement.classList
            ).toContain(
                'loading-placeholder__headline--m',
                "ngClass doesn't work"
            )
        })

})
复制代码

 

posted @   Zhentiw  阅读(262)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2019-03-24 [Functional Programming] Arrow contramap vs map and promap
2015-03-24 [React ] React Fundamentals: Component Lifecycle - Mounting Usage
2015-03-24 [React] React Fundamentals: Component Lifecycle - Mounting Basics
2015-03-24 [React] React Fundamentals: transferPropsTo
2015-03-24 [React] React Fundamentals: Add-on ClassSet() for ClassName
2015-03-24 [React] React Fundamentals: Accessing Child Properties
2015-03-24 [React] React Fundamentals: Using Refs to Access Components
点击右上角即可分享
微信分享提示