Published on

Representing a Java Style Enum in JavaScript


I am currently working on a Solidity piece of code. There is one section where I use an enum to present the current state of a piece of data for example:

    enum DirectionState {NORTH, SOUTH, EAST, WEST}

When using a web3 library to interact with enum contracts like this the value is represented as a number based on the order of the value in the enum. In the above for example NORTH is 0 and WEST is 3. Using something like truffle to test this can be a bit ugly and a pain to maintain if you try to assert on a raw number, consider the following assertion:

// when testing that a contract response is equal to NORTH

After my tests broke with one minor change I did a quick Google and came across this answer. Based on this I made a little test helper class called testHelper.js which exposes an object to represent these enum values:

module.exports = {
  messageStates: Object.freeze({
    NORTH: 0,
    SOUTH: 1,
    EAST: 2,
    WEST: 3,

Now I can update the above test to a much more readable assertion: