如何单元测试角的形式? [英] How to unit test angular form?

查看:106
本文介绍了如何单元测试角的形式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在学习AngularJS和事情进展顺利对单元测试pretty,但我已经达到了一个有点棘手现货。

I have been learning AngularJS and things have been going pretty smoothly regarding unit testing, but I've reached a bit of a tricky spot.

假设我有一个简单的形式,例如:

Suppose I have a simple form, for example:

<form name="form">
    <input type="text" name="number" ng-pattern="/^d+$/">
</form>

如果我像一个控制器测试的东西,我知道,我会写这样的事情(使用茉莉花+噶):

If I was testing something like a controller, I know that I would write it something like this (using Jasmine + Karma):

beforeEach(module('some.module'));

beforeEach(inject(/* services */) {
    /* inject necessary services */
});

it('should be invalid when given bad input', function () {
    form.number = 'Not a number';
    expect(form.number.$valid).toBeFalsy();
    expect(form.$valid).toBeFalsy();
});

但我不知道我需要注入哪些服务,我也没有任何运气在任的表格指南 NG-形式文档

一个人怎么单元测试形式角?

How does one unit test a form in Angular?

推荐答案

我不相信这是单元测试,这样的事情,但是从<一个一定的帮助的最佳方式href=\"http://stackoverflow.com/questions/15219717/to-test-a-custom-validation-angular-directive\">this在测试定制角度指令和一些实验回答,我想出了一个办法进行单元测试的形式。

I'm not convinced this is the best way to unit test something like this but with some help from this answer on testing custom angular directives and some experimentation, I figured out a way to unit test the form.

安装之后<一个href=\"https://github.com/karma-runner/karma-ng-html2js-$p$pprocessor\"><$c$c>karma-ng-html2js-$p$pprocessor并配置它,我设法得到这样一个工作单元测试:

After installing karma-ng-html2js-preprocessor and configuring it, I managed to get a working unit test like this:

var scope, form;

beforeEach(function() {
  module('my-module');
  module('templates');
});

beforeEach(inject($rootScope, $controller, $templateCache, $compile) {
    scope = $rootScope.$new()

    ctrl = $controller('MyController'), {
        "$scope": scope
    }

    templateHtml = $templateCache.get('path/to/my/template.html')
    formElem = angular.element("<div>" + templateHtml + "</div>")
    $compile(formElem)(scope)
    form = scope.form

    scope.$apply()
}

it('should not allow an invalid `width`', function() {
  expect(form.$valid).toBeTruthy();
  form.number.$setViewValue('BANANA');
  expect(form.number.$valid).toBeFalsy()
});

这篇关于如何单元测试角的形式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆