在单元测试中提交 angular 表单

Submit angular form in unit test

有没有办法在单元测试中提交表单?

我有这样的表格

<!-- notice that the controller is defined using controllerAs syntax -->
<form name="sign_up" ng-submit="auth.signUp(email, password)" role="form">

例如

SignUpCtrl = new _$controller_ 'SignUpCtrl', $scope: scope
SignUpForm = scope.sign_up # this holds the signup form

it '#signUp(email, password)', ->
  controllerSignUpMethod = sinon.spy SignUpCtrl, 'signUp'

  SignUpForm.email.$setViewValue 'em@il.com'
  SignUpForm.password.$setViewValue 'pa$$word'
  SignUpForm.confirm_password.$setViewValue 'pa$$word'
  # I can't find a way to submit the form here
  expect(controllerSignUpMethod).to.be.called

SignUpForm 是 angular fromController.. 但我找不到使用它或 scope 提交表格的方法...

最后一件事...由于一些不幸我不能使用protractor或任何其他e2e包...我唯一的选择是去使用单元测试...和视图(注册表单)可以稍后更改...因此必须存在单元测试以确保它仍在使用正确的参数调用正确的控制器... SignUpForm 是从每个测试中的模板加载的...所以它是实际形式,而不仅仅是它的模拟 $templateCache

因为控制器是使用 controllerAs: 'auth' 语法定义的..

使用以下代码:

SignUpCtrl = new _$controller_ 'SignUpCtrl as auth', $scope: scope
SignUpForm = scope.sign_up

it '#signUp(email, password)', ->
  controllerSignUpMethod = sinon.spy SignUpCtrl, 'signUp'

  SignUpForm.email.$setViewValue 'em@i.l'
  SignUpForm.password.$setViewValue 'pa$$word'
  SignUpForm.confirm_password.$setViewValue 'pa$$word'

  #=> trigger the submit event on the anugular element (or the compiled form)
  #=> you can get this using element.find('form')
  #=> or save it as the output of $compile(form)(scope)
  FormElement.triggerHandler('submit')

  expect(spy).to.be.calledWith 'em@i.l', 'pa$$word'