首页 > 解决方案 > 测试角小吃吧

问题描述

我正在制作一个简单的小吃店,其代码如下,

app.component.ts:

  ngOnInit(){
    this.dataService.valueChanges.pipe(
        filter((data) =>data=== true),
        switchMap(() => {
          const snackBarRef = this.matSnackBar.open(
            'A new value updated',
            'OK',
            {
              duration: 3000
            }
          );

          return snackBarRef.onAction();
        })
      )
      .subscribe(() => {
        this.window.location.reload();
      });
  }

app.component.spec.ts(包括服务的模拟数据)

describe('AppComponent', () => { 
  let component: AppComponent;
  let fixture: ComponentFixture<AppComponent>;
  let matSnackBarSpy: jasmine.SpyObj<MatSnackBar>;

  let a = "";
  let b = "";
  let c = "";

  const mockDataService = {
    valueChanges: of(true)
  };

  beforeEach(async(() => {
    TestBed.configureTestingModule({

    a = "Test";
    b = "X";
    c = "suc";
    matSnackBarSpy = TestBed.get<MatSnackBar>(MatSnackBar);

 })
}))

  describe('#ngOnInit()', () => {

    it('should call MatSnackBar.open()', async(done: DoneFn) => {
      const error = new HttpErrorResponse({ error: 'Some error' });

      component.ngOnInit();

      expect(mockDataService.valueChanges).toBeTruthy();
      expect(matSnackBarSpy.open(a,b,c)).toBeTruthy();

      done();
    });
  });

})

数据服务.ts

import { Observable } from 'rxjs';

export class DataService {
  valueChanges: Observable<boolean>;
}

解释:

这导致成功案例,但我永远在 chrome 中收到以下输出。

在此处输入图像描述

要求:需要涵盖当前显示警告/指示上图中未涵盖的所有测试。

上面的测试用例正在运行,但是当我们打开组件时,测试覆盖率仍然显示功能未覆盖,并且语句未覆盖警告。index.html

标签: angulartypescriptunit-testingjasminekarma-jasmine

解决方案


所以,你基本上应该测试matSnackBar方法是否被正确调用。的测试行为matSnackBar不是单元测试。

尝试

class MatSnackBarStub{
  open(){
    return {
      onAction: () => of({})
    }
  }

}

component.spec文件中

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [SomeComponent],
      providers ; [ { provide: MatSnackBar , useClass: MatSnackBarStub }]
    }).compileComponents();
  }));

  it('should create', () => {
    spyOn(component.matSnackBar,"open").and.callThrough();
    component.ngOnInit();
    expect(component.matSnackBar.open).toHaveBeenCalled();
    // you can also use ".toHaveBeenCalledWith" with necessary params
  });

我建议你看看这个与使用 jasmine 和 karma 进行单元测试相关的文章集合。有一篇关于如何使用存根和间谍的文章。我希望这会有所帮助


推荐阅读