【问题标题】:getting Error: Expected spy onSubmit to have been called得到错误:预期的间谍 onSubmit 已被调用
【发布时间】:2018-07-19 23:15:04
【问题描述】:

我是 Angular 新手,并尝试使用 karma-jasmine 在 Angular 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 函数。

【问题讨论】:

    标签: karma-jasmine angular5


    【解决方案1】:

    我在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 的一些说明。希望能帮助到你。

    【讨论】:

      猜你喜欢
      • 2023-04-06
      • 1970-01-01
      • 2017-11-18
      • 1970-01-01
      • 1970-01-01
      • 2019-02-05
      • 1970-01-01
      • 2018-04-08
      • 1970-01-01
      相关资源
      最近更新 更多