Nachdem ich angefangen habe, die C64 CPU Emulation zu programmieren, habe ich schnell festgestellt das ich ein Testframework benötigte. Daher beschreibe ich hier die Einrichtung und die Erstellung von einem Test für eine einfache Memory-Klasse.

JavaScript Unit-Tests

Installation des Test Runners (mocha) und des Testframeworks (chai)

$ yarn add -D mocha chai 
# Typescript Support
$ yarn add -D @types/mocha @types/chai ts-node

$ mkdir src/test
src/Memory.ts:
class Memory {
    private memBuffer : ArrayBuffer;
    private memory : Uint8Array;

    constructor(size : number) {
        this.memBuffer = new ArrayBuffer(64 * 1024);
        this.memory = new Uint8Array(this.memBuffer);

        for (let i = 0; i < this.memory.length; i++ ) {
            this.memory[i] = 0;
        }
    }

    public readByte(address : number) : number {
        return this.memory[address];
    }

    public writeByte(address : number, value : number) : void {
        this.memory[address] = value;
    }

    public readWord(address : number) : number {
        return this.memory[address + 1] << 8 | this.memory[address];
    }

    public writeWord(address : number, value : number) : number {
        this.memory[address + 1] = (value & 0xff00) >> 8;
        this.memory[address] = value & 0x00ff;
    }

    public getMemory() : Uint8Array {
        return this.memory;
    }
}

export default Memory;
src/test/Memory.spec.ts:
import Memory from '../Memory';

import {assert} from 'chai';
const mem = new Memory(64 * 1024);

describe('Memory tests', function() {
  it('should write a byte', function() {
    mem.writeByte(0x0000, 0x5f);
    assert.equal(mem.getMemory()[0], 0x5f);
  });

  it('should read a byte', function() {
    mem.writeByte(0x0001, 0x7f);
    assert.equal(mem.readByte(1), 0x7f);
  });

  it('should read a word', function() {
    mem.writeByte(0x0000, 0x22);
    mem.writeByte(0x0001, 0x11);
    assert.equal(mem.readWord(0), 0x1122);
  });

  it('should write a word', function () {
    mem.writeWord(0x0100, 0x3344);
    assert.equal(mem.readByte(0x0100), 0x44);
    assert.equal(mem.readByte(0x0101), 0x33);
  });

});

Starten des Test-Runners:

$ ./node_modules/mocha/bin/mocha --require ts-node/register src/**/*.spec.ts

  Memory tests
    ✓ should write a byte
    ✓ should read a byte
    ✓ should read a word
    ✓ should write a word

  4 passing (11ms)
package.json:
    "prod": "npm-run-all clean:prod build:prod",
    "run:dev": "webpack-dashboard --minimal -- webpack-dev-server --hot --config webpack.config.js --watch",
    "run:prod": "webpack-dev-server --hot --config webpack.config.js --watch --env.NODE_ENV=production",
    "start": "npm run run:dev",
/* begin neuer code */
    "test": "mocha --require ts-node/register src/**/*.spec.ts"
/* ende neuer code */
  },

Die Tests mittels yarn test ausführen.

Next Post Previous Post