Angular 2 RC5测试detectChanges无效

时间:2016-08-29 12:05:36

标签: angular angular2-forms angular2-testing

我正在使用以下界面构建loginform组件:

<login-form onlogin="submit()"></login-form>

这就是测试代码:

  it("Should send credentials out of the component", async(() => {
    TestBed.compileComponents().then(() => {
      const fixture = TestBed.createComponent(LoginFormComponent);
      let component = fixture.componentInstance;
      spyOn(component.onlogin, "emit");

      let domRef = fixture.nativeElement;
      domRef.querySelector("input[name='username']").value = "test@test.com";
      domRef.querySelector("input[name='password']").value = '1234';
      domRef.querySelector("form").dispatchEvent(new Event('submit'));

      fixture.detectChanges();

      let expectedSubmitData:UserCredentials = {
        username: "test@test.com",
        password: "1234"
      };
      expect(component.onlogin.emit).toHaveBeenCalledWith(expectedSubmitData);
    });
  }));

我收到了这条消息:

Expected spy emit to have been called with [ Object({ username: 'test@test.com', password: '1234' }) ] but actual calls were [ Object({ username: '', password: '' }) ]

那么,填充输入值的方法是什么,模型会检测到这些变化?

1 个答案:

答案 0 :(得分:1)

请尝试做以下事情,它对我有用!!。

let domRef = fixture.nativeElement;
let userInput = domRef.querySelector("input[name='username']")
userInput.value = "test@test.com";
userInput.dispatchEvent(new Event('input'));
let passwordInput = domRef.querySelector("input[name='password']")
passwordInput.value = '1234';
passwordInput.dispatchEvent(new Event('input'));
fixture.detectChanges();
domRef.querySelector("form").dispatchEvent(new Event('submit'));
let expectedSubmitData:UserCredentials = {
   username: "test@test.com",
   password: "1234"
};
expect(component.onlogin.emit).toHaveBeenCalledWith(expectedSubmitData);