Yesterday I wrote about making my first filter for AngularJS. This morning I created a test for it. Here’s the pattern that I followed.

index.html.haml
1
2
3
4
5
6
7
!!!
%html(ng-app="ExampleApp")
  %head
  %body
    .row-fluid
      %span(ng-bind-html-unsafe="(1 > 2) | whatAmI")
      %span(ng-bind-html-unsafe="(1 < 2) | whatAmI")
controller.js.coffee
1
2
3
4
5
6
7
8
app = angular.module("ExampleApp", [])

app.filter "whatAmI", ->
  (statement) ->
    if statement
      "<span class="answer-true">I'm true</span>"
    else
      "<span class="answer-false">I'm false</span>"
controllerSpec.js.coffee
1
2
3
4
5
6
7
8
9
10
11
12
#= require_tree ../../app/assets/javascripts
#= require angular-resource
#= require angular-mocks

describe "whatAmI Filter", ->
  beforeEach angular.mock.module("ExampleApp")

  it "returns I'm true if the expression is true", inject((whatAmIFilter) ->
    expect(whatAmIFilter(true)).toBe "<span class="answer-true">I'm true</span>")

  it "returns I'm false if the expression is false", inject((whatAmIFilter) ->
    expect(whatAmIFilter(false)).toBe "<span class="answer-false">I'm false</span>")

Notes

  • I’m using JasmineRice to test Angular in my Rails app.

  • Notice that the mock name ExampleApp corresponds to the name of the app. This is not optional. You cannot mock something that doesn’t exist.

  • Filter should be appended to the name of your filter when evaluating it directly in the test.

Comments