得到错误:已经调用了预期的间谍onSubmit

时间:2018-02-12 11:33:46

标签: karma-jasmine angular5

我是角色的新手,并尝试使用karma-jasmine以角度5编写单元测试。

我有一个登录页面,其中包含2个参数用户名和密码,而onSubmit()是用于调用api来验证用户的函数。检查下面的文件以获取登录组件。

login.component.ts

@Component({

  selector: 'app-login',

  templateUrl: './login.component.html',

  styleUrls: ['./login.component.scss']

})

export class LoginComponent implements OnInit {

  myform: FormGroup;

  username: FormControl;

  password: FormControl;

  errMsg: string;

  loginErr: boolean;


  model: any = {};

  constructor(

    private http: Http,

    private router: Router

  ) {
  }

  ngOnInit() {

    this.createFormControls();

    this.createForm();
  }


  createFormControls() {

    this.username = new FormControl('', Validators.required);

    this.password = new FormControl('', [

      Validators.required,

      Validators.minLength(6)

    ]);

  }

  createForm() {

    this.myform = new FormGroup({

      username: this.username,

      password: this.password

    });
    enter code here

  }

  onSubmit() {
    this.errMsg = "";
    if (this.myform.valid) {

      var data = {
        'Username': this.username.value,
        'Password': this.password.value
      };

      var options = {
        type: "POST",
        url: GlobalVariable.BASE_API_URL + "authentication/authenticate-user",
        content: "application/json; charset=utf-8",
        contentType: 'application/json',
        async: false,
        processing: true,
        crossDomain: true,
        xhrFields: { withCredentials: true },
        body: JSON.stringify(data),
      };

      let headers = new Headers({ 'Content-Type': 'application/json' });

      this.http.post(options.url, options.body, { headers: headers }).subscribe((data) => {

        console.log(JSON.parse(data['_body']));

      }, (err) => {
        console.log(data['_body']);
        this.errMsg = "Invalid Login Attempt.";
      }, () => {
        console.log("All Good With The Data")
      });
    }
    else
    {

     }
  }

}

现在我正在尝试为上面的文件编写单元测试,请在spec.ts文件下面查看示例代码

**** **** login.component.spec.ts

describe('LoginComponent', () => {

  let component//: LoginComponent;

  let fixture//: ComponentFixture<LoginComponent>;

   beforeEach(async(() => {

      TestBed.configureTestingModule({
      declarations: [ LoginComponent],
      imports: [ReactiveFormsModule, HttpModule, AppRoutingModule, RouterModule, FormsModule],
      providers: [
        {provide: Globals, useValue: GlobalVariable.BASE_API_URL},
        {provide: APP_BASE_HREF, useValue: '/'}
      ],
    })
    .compileComponents();
  }));

  beforeEach(() => {

    fixture = TestBed.createComponent(LoginComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create login component', () => {

    spyOn(component,'onSubmit').and.callThrough();
    component.username = 'username';
    component.password = '12345678';
    expect(component.onSubmit).toHaveBeenCalled();
  });
});

当我运行此单元测试时,它显示错误为附加图像,请告诉我我的代码中有什么错误。如何编写单元测试来通过传递用户名和密码来验证用户,并调用onSubmit函数。

enter image description here

1 个答案:

答案 0 :(得分:0)

我在Angular 6应用程序的组件测试中遇到了这个问题。我所做的是,将spyOn部分移到了组件部分之前。之后,我的测试运行良好。

之前

beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [HomeComponent, SingleNewsComponent, NewsComponent, DummyComponent],
      imports: [MatCardModule, MatSelectModule, MatButtonModule, HttpModule, NewsRouterModule, BrowserAnimationsModule],
      providers: [
        { provide: APP_BASE_HREF, useValue: '/' },
        ApiService]
    })
      .compileComponents();
    spyOn(apiService, 'post').and.returnValue(new Observable<any>());
    fixture = TestBed.createComponent(SingleNewsComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    apiService = TestBed.get(ApiService);
  }));

之后

.compileComponents();
apiService = TestBed.get(ApiService);
spyOn(apiService, 'post').and.returnValue(new Observable<any>());
fixture = TestBed.createComponent(SingleNewsComponent);
component = fixture.componentInstance;
fixture.detectChanges();

如您所见,我已经更改了服务间谍的顺序。感谢Supamiu对此here进行了介绍。希望能帮助到你。