Wednesday, March 14, 2012

Unit Testing JavaScript with Jasmine

The lack of good unit tests integrated with Maven was one of the things that kept me away from serious JavaScript development. So recently, I tried out Jasmine for unit testing JavaScript code. This is pretty cool stuff.

Add this snippet to pom.xml:

  <build>
    <plugins>
      <plugin>
        <groupid>com.github.searls</groupid>
        <artifactid>jasmine-maven-plugin</artifactid>
        <version>1.1.0</version>
        <executions>
          <execution>
            <goals>
              <goal>test</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          
        </configuration>
      </plugin>
    </plugins>
  </build>
Then I can write a unit test specification like this:

describe("LinearMemory64K", function() {
    var memory;
    
    beforeEach(function() {
        memory = new LinearMemory64K();
    });
    
    it("can be read", function() {
        var data = memory.read(0x8000);
        expect(data).toEqual(0x00);
    });
    
    it("can be written to", function() {
        memory.write(0x8000, 0xEA);
        var data = memory.read(0x8000);
        expect(data).toEqual(0xEA);
    });
    
    it("has 16 address lines", function() {
        memory.write(0x18000, 0xEA);
        var data = memory.read(0x8000);
        expect(data).toEqual(0xEA);
    });


    it("has 8 data lines", function() {
        memory.write(0x8000, 0x1EA);
        var data = memory.read(0x8000);
        expect(data).toEqual(0xEA);
    });
    
    it("handles negative numbers", function() {
        memory.write(0x8000, -1);
        var data = memory.read(0x8000);
        expect(data).toEqual(0xFF);
    });


    it("uses two's compliment to represent negative numbers", function() {
        memory.write(0x8000, -2);
        var data = memory.read(0x8000);
        expect(data).toEqual(0xFE);
    });
});
In my example, I've used the toEqual() matcher, but the Jasmine Matcher API offers a lot more. I'm looking forward to writing a lot more JavaScript code in the future.

No comments:

Post a Comment