在服务规格中测试SnackBar的出现

时间:2019-03-14 13:12:28

标签: angular unit-testing jasmine

因此,我正在为Angular应用程序编写单元测试。我有这个errorHandlerService,带有handle()函数,该函数接收String或Error类,对其进行处理,最后根据错误类型打开一个带有不同消息的SnackBar。

error-handler.service.ts

@Injectable({
  providedIn: 'root'
})
export class ErrorHandlerService {

  constructor(
    public snackBar: MatSnackBar
  ) { }

   handle(errorResponse: any) {
    let msg: string;

    if (typeof errorResponse === 'string') {
      msg = errorResponse;

    } else if (errorResponse instanceof HttpErrorResponse
      && errorResponse.status >= 400 && errorResponse.status <= 499) {
        msg = 'Error processing your request.';

        if (errorResponse.status === 403) {
          msg = 'You're not allowed to execute this action.';
        }

        console.error('Error occurred', errorResponse);
     } else {
        msg = 'Error processing remote service. Try again later.';
        console.error('Error occurred', errorResponse);
     }

    this.snackBar.open(msg);
  }
}

我的测试方法仅是考虑到将要发生的情况,以评估快餐栏是否已打开。但是我该怎么办呢?这是我的.spec.ts文件

error-handler.service.spec.ts

describe('ErrorHandlerService', () => {
  beforeEach(() => TestBed.configureTestingModule({
    imports: [RouterTestingModule],
    providers: [
      { provide: MatSnackBar, useValue: {} }
    ]
}));

it('should be created', () => {
 const service: ErrorHandlerService = TestBed.get(ErrorHandlerService);
 expect(service).toBeTruthy();
});

it('should call handle function and check snackBar occurrence', () => {
  const service: ErrorHandlerService = TestBed.get(ErrorHandlerService);
  service.handle('testing error');

  expect(service.snackBar.open).toHaveBeenCalled();
 });
});

感谢您的帮助。谢谢

2 个答案:

答案 0 :(得分:0)

首先,我将在beforeEach上方声明服务并在其中进行初始化:

 let service: ErrorhandlerService;
 beforeEach(() => {.... service = TestBet.get(ErrorHandlerService); })

在其中我会这样做:

let spy = spyOn(service.snackBar, "open")

service.handle(msg);

然后期望:

(spy).toHaveBeenCalledWith(msg)

建议:我会在其中加上一些特定的名称。像Service_MethodToTest_ExpectOpenToBeCalled之类的东西。

答案 1 :(得分:0)

感谢Robert Tab的帮助!工作正常。我只需要进行一些调整,如下所示:

error-handler.service.ts(在文件末尾)

   this.callSnackBar(msg);
 }

 callSnackBar(msg: string) {
   this.snackBar.open(msg);
 }

在spec.ts文件中,我做到了:

error-handler.service.spec.ts

beforeEach(() => {
  service = TestBed.get(ErrorHandlerService);
});

...

it('should call handle function and check snackBar occurrence', () => {
  const spy = spyOn(service, 'callSnackBar');
  const msg = 'Service_MethodToTest_ExpectOpenToBeCalled';

  service.handle(msg);
  expect(spy).toHaveBeenCalledWith(msg);
});