在单元测试中提交角形

时间:2015-02-27 01:00:16

标签: angularjs unit-testing angularjs-ng-form karma-mocha ng-submit

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

我有一个像

这样的表格
<!-- 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

1 个答案:

答案 0 :(得分: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'