angular - 测试 Angular snackbar

标签 angular typescript unit-testing jasmine karma-jasmine

我正在制作一个简单的 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>;
}

说明:

  • 我正在使用的服务具有属性 valueChanges类型为Observable<boolean> .

  • component.ts ,我得到的值变化如上所述,我收到的最终结果是 bool 值 true并且 snackbar 也打开了,一切都工作正常。

  • 现在我正在实现上述测试用例,如compoenent.spec.ts ,

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

这会导致成功,但我永远在 Chrome 中收到以下输出。

enter image description here

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

上述测试用例正在运行,但测试覆盖率在我们打开时仍显示函数未覆盖以及语句未覆盖警告 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 的单元测试相关。有一篇文章介绍如何使用 stub 和 spy 。我希望这会有所帮助

关于angular - 测试 Angular snackbar ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61929570/

相关文章:

angular - 无法以 Angular 5 从一页导航到另一页

html - 使用 Angular 2 动画创建 Accordion 式导航

angular - Firebase : firebase. Promise<any> 与 Rxjs Promise<any> 的兼容性

python - 如何测试模型是否在 FastAPI 路由中使用?

azure - coverlet 不会在 azure devops 中创建报告

java - 使用模拟验证错误消息,其中结果可以根据 id 更改

asp.net-mvc - Angular4 + MVC + cli + 使用从 cli 构建命令生成的 dist 文件夹进行部署

html - 如何以 Angular 制作嵌套表结构?

javascript - React map 内 JSX 元素的展开操作

node.js - 从 Cloud Functions Realtime Database 中的子引用获取父 Node 的原始值 "val()"数据