-hwava
Last Updated: February 25, 2016
·
5.343K
· gursesl
29eb317d68143e49df5ce475c2b798ca

Beginners' Guide to Writing Jasmine Tests in CoffeeScript

Start with src/Calculator.coffee:

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) ->
        num1/num2

Now, spec/CalculatorSpec.coffee:

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/Calculator.coffee
$ coffee -cwb spec/CalculatorSpec.coffee

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

<!DOCTYPE HTML>
<html>
<head>
  <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>

</head>

<body>
</body>
</html>
Say Thanks
Respond

1 Response
Add your response

12310
63f769729b047cdde2a12bec3871b334

Hi!
Thank you!
It works for me now :)

over 1 year ago ·