如何在 Angular 中使用 Jasmine Karma 对 MatSnackbar 进行单元测试

How to unit test MatSnackbar using Jasmine Karma in Angular

我想对此 onSubmit 函数执行单元测试,其中肯定提交导致 MatSnackbar 显示消息“已成功提交”。我是 Jasmine Karma 的新手,请指导我在这种情况下测试 MatSnackbar。

Component.ts

import { MatSnackBar } from "@angular/material/snack-bar";

  constructor(
    private snackBar: MatSnackBar,
    private auth: AuthenticateService,

  ) {}
...
...
  onSubmit(e) {
    const newYellow = {
      G1: e.value.Yellow_G1,
      G2: e.value.Yellow_G2,
      G3: e.value.Yellow_G3,
      G4: e.value.Yellow_G4,
      B1: e.value.Yellow_B1,
      B2: e.value.Yellow_B2,
      B3: e.value.Yellow_B3,
      B4: e.value.Yellow_B4,
    };
    console.log(newYellow);
    this.auth.submitnominYellow(newYellow).subscribe(
      (res) => {
        console.log(res);
        this.snackBar.open("Submitted Successfully", "", {
          duration: 2000,
        });
      },
      (error) => {
        console.log(error);
      }
    );
  }

这是 submitnomin 函数的代码。 auth.service.ts

submitnominYellow(inpobj) {
    console.log(inpobj);
    return this.http.post(environment.apiUrl + '/api/customize/yellow', inpobj);
}

我的单元测试用例有点像这样
component.spec.ts

    const mockSnackbarMock = jasmine.createSpyObj(['open']);
    mockSnackbarMock.open
    
    const mockopblue =
      {
        success: true
    }
    
    const MockAuthService = {
      submitnominYellow:(id) => (mockopblue),
      getuser:() => (undefined)
    
    };
...
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ YellowCustomizeComponent ],
      imports: [HttpClientTestingModule, MatSnackBarModule, FormsModule, RouterTestingModule],
      providers:[{provide: MatSnackBar, useValue: mockSnackbarMock},
      {provide: AuthenticateService, useValue: MockAuthService}
      ]

    })
    .compileComponents();
  }));
...

          fit('should open the snack bar with correct arguments when form submitted', () => {
            const e =  {
              value:{
                Yellow_G1: "YGirlName1",
                Yellow_G2: "GirlName2",
                Yellow_G3: "GirlName3",
                Yellow_G4: "GirlName4",
                Yellow_B1: "BoyName1",
                Yellow_B2: "BoyName2",
                Yellow_B3: "BoyName3",
                Yellow_B4: "BoyName4",
              }
              
            };
            component.onSubmit(e)
            console.log('mockSnackbarMock',mockSnackbarMock)
            // console.log('yellow onsubmit',component.onSubmit(e)); 
            expect(mockSnackbarMock.open).toHaveBeenCalledWith("Submitted Successfully", "", );
         })

在测试中,可以更改依赖项注入配置,以便提供模拟实例而不是 SnackBar 实例。方法是这样的:

const mockSnackbarMock = jasmine.createSpyObj(['open']);
mockSnackbarMock.open

await TestBed.configureTestingModule({
            declarations: [
                ...
            ],
            providers: [
                {provide: MatSnackBar, useValue: mockSnackbarMock},
            ],
            imports: [
                ...
            ],
        }).compileComponents();

稍后在测试所有触发小吃店的动作后,您可以检查打开方法是否被正确调用:

it('should open the snack bar with correct arguments when form submitted', () => {
   //emulate submission

   expect(mockSnackbarMock.open).toHaveBeenCalledWith("Submitted Successfully", "", {duration: 2000});
})