如何在Angular和typecript的类中编写单元测试静态方法

285 阅读2分钟

在本教程中,你学到了如何对一个typescript类的静态方法进行单元测试。它包括一个如何在Angular中使用静态方法测试一个组件的例子。

让我们在typescript中声明一个带有静态方法的ES6类。

export class StaticClass {
    static getMessage(name: string): String {
        return 'Hi' + name + 'Welcome to my blog';
    }
}

下面是一个带有静态方法的ES6类的单元测试类。

  • jasmine API有spyon ,可以用类的实例或类本身模拟方法。
  • 它接受的参数是withArgs
  • 返回值是用returnValue
  • 并接受参数和返回值
  • 单元测试一个函数是将不同的值
  • 并断言以下内容
    • 传递给静态函数的值,并比较预期值和实际值
    • 使用toHaveBeenCalled 方法检查静态函数是否被调用。
it('Calling getMessage', () => {
        let spyStaticClass = spyOn(StaticClass, "getMessage")
            .withArgs("John").and.returnValue("welcome");
        StaticClass.getMessage("John")
        expect(StaticClass.getMessage).toHaveBeenCalled();
        expect(StaticClass.getMessage).toHaveBeenCalledWith("John");
        expect(StaticClass.getMessage("John")).toEqual("welcome");

    })

使用静态方法对Angular组件进行单元测试

假设你在Angular组件中使用一个静态类,在这个例子中,你在ngOnInit()方法中调用静态方法。

import { Component } from '@angular/core';
import { StaticClass } from './StaticClass';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = '';

  constructor() { }

  ngOnInit() {
    this.title = StaticClass.getMessage('john');
  }
}
}

下面是一个单元测试,用于测试组件中的静态函数。

it('should call ngInit and call static methods ', () => {

    const fixture = TestBed.createComponent(AppComponent);
    const component = fixture.componentInstance;

    let spyStaticClass = spyOn(StaticClass, "getMessage").and.returnValue("welcome")
    StaticClass.getMessage("John")
    fixture.detectChanges();

    component.ngOnInit();
    expect(StaticClass.getMessage).toHaveBeenCalled();
    expect(StaticClass.getMessage).toHaveBeenCalledWith("John");
    expect(StaticClass.getMessage("John")).toEqual("welcome");
  });

在Jest框架中模拟静态方法

我们有很多方法可以进行模拟

使用jest spyon方法,其作用与jasmine spyon方法相同。

it('getMessage', () => {
        let spyStaticClass = jest.spyOn(StaticClass, "getMessage")
            .withArgs("John").and.returnValue("welcome");
        StaticClass.getMessage("John")
        expect(StaticClass.getMessage).toHaveBeenCalled();
        expect(StaticClass.getMessage).toHaveBeenCalledWith("John");
        expect(StaticClass.getMessage("John")).toEqual("welcome");

})

另一种方法是使用jest实现的模拟类

  • 使用jest.Mocked语法为类创建一个mock类。
  • 为静态方法写一个模拟实现
  • 检查静态类的断言是否被调用。
it('getMessage with jest', () => {
        const MockStaticClass = StaticClass as jest.Mocked;
        MockStaticClass.getMessage.mockImplementation((item) => 'Welcome' + item);
        expect(MockStaticClass.getMessage).toHaveBeenCalled();

    })

总结

你学会了使用jasmine和jest API对es6类中的静态方法进行模拟单元测试。