【问题标题】:How should I write out the unit testing if statement for this if statement for these query params?我应该如何为这些查询参数写出这个 if 语句的单元测试 if 语句?
【发布时间】:2021-07-13 19:01:51
【问题描述】:

.ts 文件:

ngOnInit(): void {
    if (
      this.activatedRoute.snapshot.queryParamMap.has('esign') && 
      this.activatedRoute.snapshot.queryParamMap.has('registration')
    ) {
      this.eSignAndRegistration = true;
    }

.spec.ts 文件:

  let esign_registration = false;
  const mockActivatedRoute = {
    snapshot: {
      queryParamMap: {
        has: (response) => {
          if (response == 'esign' && response == 'registration') {
            return esign_registration;
          }

测试:

  fit("should show the 1st mat-card if the param is 'esign&registration'", () => {
    esign_registration = true;
    fixture.detectChanges();
    component.ngOnInit();
    fixture.detectChanges();
    const compiled = fixture.nativeElement;
    expect(component.eSignAndRegistration).toBeTruthy();
  });

错误不断出现“预期未定义为真实”。 'has' if 语句需要如何编写才能使单元测试正常工作?我试过了

if (response == 'esign' && 'registration')

if (response == 'esign&registration')

以及其他各种方法,但它们都一直给出相同的错误。

【问题讨论】:

  • 没有真正回答你的问题,但你应该使用工具来简化路由参数的模拟,而不是自己创建一个完整的模拟。观众图书馆可以提供帮助。我相信最近版本的 Angulzr 甚至内置了一些东西。

标签: angular unit-testing if-statement query-parameters


【解决方案1】:

response == 'esign' && response == 'registration'

尝试将&& 更改为||。如果响应是一个字符串,它只能是其中之一。

【讨论】:

  • 这有助于修复该测试用例,但它给“设计”和“注册”带来了这个问题。快照:{ queryParamMap:{ 有:(response) => { if (response == 'esign' || response == 'registration') { return esign_registration; } if (response == 'registration') { 返回注册; } if (response == 'esign') { return esign; } if (response == 'css') { return css; } }, },
  • 现在这取决于你想做什么。我猜你想要单独的 if 声明和注册?然后删除第一个 if 语句(不知道它是干什么用的),并在你的测试中分配 esign = trueregistration = true
猜你喜欢
  • 1970-01-01
  • 2021-06-07
  • 1970-01-01
  • 2021-09-19
  • 2013-07-28
  • 2021-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多