【问题标题】:Submit angular form in unit test在单元测试中提交角度形式
【发布时间】:2015-04-29 14:46:34
【问题描述】:

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

我有一个类似的表格

<!-- 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

【问题讨论】:

  • 好的,我现在知道了。你不能只是 SignUpCtrl.signUp() 吗?还是 SignUpCtrl.auth.signUp()?
  • 这是视图..它使用控制器作为语法...所以auth.signUp调用SignUpCtrl.SignUp方法...视图将由设计师稍后修改...所以我们必须确保它在修改后仍然有效
  • 所以SignUpForm 加载模板并对模型的验证做一些单元测试......然后它必须确保它调用正确的控制器方法(SignUpCtrl.signUp(email, password)
  • 哦,好吧,我不知道这个问题的答案,但我找到了这个link。也许它可以帮助?它正在测试一个指令,但它非常相似。使用jqlite.triggerHandler('submit'),但我不确定是什么。 SignUpForm.triggerHandler('submit') 也许?祝你好运。
  • 这真是个好消息,很高兴它有帮助。

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


【解决方案1】:

因为控制器是使用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'

【讨论】:

    猜你喜欢
    • 2016-12-19
    • 2018-10-26
    • 2017-09-17
    • 1970-01-01
    • 2018-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多