Last Updated: February 25, 2016
· gursesl

Beginners' Guide to Writing Jasmine Tests in CoffeeScript

Start with src/

class Calculator
    constructor: ->
        console.log "Instantiated new Calculator instance"

    add: (num1, num2) ->
        num1 + num2

    subtract: (num1, num2) ->
        num1 - num2

    multiply: (num1, num2) ->
        num1 * num2

    divide: (num1, num2) ->

Now, spec/

describe 'Calculator', () ->
    calc = {}
    beforeEach ->
        calc = new Calculator()

    it 'should be able to add two numbers', () ->
        expect(calc.add 3,4 ).toBe 7

    it 'should be able to subtract two numbers', () ->
        expect(calc.subtract 32,18 ).toBe 14

    it 'should be able to multiply two numbers', () ->
        expect(calc.multiply 6,4 ).toBe 24

    it 'should be able to divide two numbers', () ->
        expect(calc.divide 32,8 ).toBe 4

    it 'should be able to divide to zero and receive Infinity', () ->
        expect(calc.divide 32,0 ).toBe Infinity

    it 'should be able to divide to Infinity and receive zero', () ->
        expect(calc.divide 32,Infinity ).toBe 0

Compile the CoffeeScript files to JavaScript by enabling bare. Otherwise, the code gets wrapped into a function call, which throws Jasmine off

$ coffee -cwb src/
$ coffee -cwb spec/

Finally, add the two compiled JavaScript files to the Jasmine runner, SpecRunner.html:

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>Jasmine Spec Runner v2.0.0</title>

  <link rel="shortcut icon" type="image/png" href="lib/jasmine-2.0.0/jasmine_favicon.png">
  <link rel="stylesheet" type="text/css" href="lib/jasmine-2.0.0/jasmine.css">

  <script type="text/javascript" src="lib/jasmine-2.0.0/jasmine.js"></script>
  <script type="text/javascript" src="lib/jasmine-2.0.0/jasmine-html.js"></script>
  <script type="text/javascript" src="lib/jasmine-2.0.0/boot.js"></script>

  <!-- include source files here... -->
  <script type="text/javascript" src="src/Calculator.js"></script>

  <!-- include spec files here... -->
  <script type="text/javascript" src="spec/CalculatorSpec.js"></script>



1 Response
Add your response

Thank you!
It works for me now :)

over 1 year ago ·