【问题标题】:Angular testing: Expected spy AuthenticationService.checkUsername to have been called角度测试:预期间谍 AuthenticationService.checkUsername 已被调用
【发布时间】:2019-02-24 00:35:51
【问题描述】:

我正在学习 Angular 测试,但到目前为止它非常令人沮丧。我想测试我的注册组件,但它给了我以下错误。

预计间谍 AuthenticationService.checkUsername 是 调用。

这是我要测试的组件。我目前正在测试checkUniqueUsername() 方法是否按计划工作。当我调用消息时,我希望属性 uniqueUsernameMessage 在 authService.checkUsername() 方法返回 {obj: true} 时包含字符串 'already exists'

不幸的是,它返回了上述错误,并且对于属性 uniqueUsernameMessage 的值,它返回 undefined 而不是预期的 .contains(already exists)。

谁能帮我弄清楚我哪里出错了?

Signup.component.ts

@Component({
    selector: 'app-sign-up',
    templateUrl: 'sign-up.component.html',
    styleUrls: ['sign-up.component.css']
})

export class SignUpComponent implements OnInit {

    mySignupForm: FormGroup;
    countries = countries;
    uniqueUsernameMessage;
    uniqueEmailMessage;
    formSubmitted = false;
    @Output() closeSubmenu = new EventEmitter();

    constructor(
        private authService: AuthenticationService,
        private route: Router,
        private navigationService: NavigationService){}


    ngOnInit() {
        this.mySignupForm = new FormGroup({
            firstName: new FormControl(null, Validators.required),
            lastName: new FormControl(null, Validators.required),
            username: new FormControl(null, [Validators.required, Validators.minLength(5), Validators.maxLength(15)]),
            birthDate: new FormControl(null, Validators.required),
            password1: new FormControl(null, [Validators.required, Validators.minLength(6), Validators.maxLength(15)]),
            password2: new FormControl(null, Validators.required),
            email: new FormControl(null, [Validators.required, Validators.email]),
            country: new FormControl(null, Validators.required),
            house: new FormControl(null, Validators.required)
        })
    }

    checkUniqueUsername() {

        if ((this.mySignupForm.value.username >= 5 && this.mySignupForm.value.username <= 15) || null ){
            this.authService.checkUsername(this.username.value)
                .pipe(debounceTime(500))
                .subscribe((result: any) => {
                    if (result.obj) {
                        console.log('result', result);
                        this.uniqueUsernameMessage = "This username already exists. Please pick another one."
                    } else {
                        this.uniqueUsernameMessage = null;
                    }
                })
        }
    }
}

signup.component.spec.ts

describe('signup', () => {
  let component: SignUpComponent;
  let fixture: ComponentFixture<SignUpComponent>;
  let authService;

  beforeEach(async(() => {
    const authServiceSpy = jasmine.createSpyObj('AuthenticationService', ['checkUsername', 'checkEmailUniqueness', 'signup']);

    TestBed.configureTestingModule({
      declarations: [SignUpComponent],
      providers: [
        {
          provide: AuthenticationService,
          useValue: authServiceSpy
        },
        NavigationService
      ],
      imports: [
        RouterTestingModule],
      schemas: [NO_ERRORS_SCHEMA]
    })
      .compileComponents();

    authService = TestBed.get(AuthenticationService);
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(SignUpComponent);
    component = fixture.componentInstance;
    // fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should warn user if username already exists', fakeAsync(() => {
      const fakeUsername = "testUsername"
      authService.checkUsername.and.returnValue(of({obj: true}));

      fixture.detectChanges();

      component.mySignupForm.value.username = fakeUsername;

      fixture.detectChanges();
      component.checkUniqueUsername();

      tick(500);

      expect(authService.checkUsername).toHaveBeenCalled();
      expect(component.uniqueUsernameMessage).toContain('already exists');
    })
  )
});

【问题讨论】:

    标签: javascript angular testing jasmine karma-runner


    【解决方案1】:

    这一行:

    component.mySignupForm.value.username = fakeUsername;

    不会更改 FormControl 的值。 username 的值仍然是 null。因此,当您检查其有效性时,if 内部的条件为false。

    反应形式是不可变的。如果要为任何 FormControl 设置新值,应使用.setValue() 完成。

    像这样:

    component.mySignupForm.get('username').setValue(fakeUsername);

    希望这会有所帮助:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-04
      • 1970-01-01
      • 2017-11-18
      • 1970-01-01
      • 1970-01-01
      • 2020-05-11
      • 1970-01-01
      相关资源
      最近更新 更多