2

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

我有一个像

<!-- 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是有角度的fromController..但我找不到使用它或scope提交表单的方法...

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

4

1 回答 1

3

因为控制器是使用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'
于 2015-02-27T02:02:31.270 回答