测试 angular 零食

Test angular snackbar

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

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

})

data.service.ts

import { Observable } from 'rxjs';

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

解释:

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

要求: 需要涵盖当前显示的所有测试 warning/indication 或上图中未涵盖的..

上面的测试用例是 运行 但测试覆盖率仍然显示 function not covered 并且 statement not covered warning when we打开组件的 index.html

因此,您基本上应该测试 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
  });

我建议您看一下 this collection of articles 与使用 jasmine 和 karma 进行单元测试相关的内容。有一篇文章介绍如何使用存根和间谍。我希望这会有所帮助