Search code examples
unit-testinglualua-busted

Busted has_error causes tests to error


I am attempting to use busted for unit tests on a lua project. I have a module that looks something like this:

-- src/rom/apis/display.lua

local _displayModes = {
  single = 1,
  mirrored = 2,
  extended = 3,
  immersive = 4
}

local _validMode = function(mode)
  retVal = false
  for k,v in pairs(_displayModes) do
    if mode == v then retVal = true break end
  end
  return retVal
end

local _setMode = function (mode)
  if _validMode(mode) then
    _config.mode = mode
  else
    error("INVALID DISPLAY MODE: "..mode)
  end
end

display = {
  mode = _displayModes,
  setMode = _setMode
}

in my spec I am trying to assert that setMode returns an error:

local displayModule = require("rom/apis/display")
describe("#API #Display", function()
  describe("with single monitor", function()
    setup(function()
      local _p = {
        monitor = {'foo'}
      }
      mockPeripherals(_p)
    end)

    it("should not setMode with invalid mode", function()
      assert.has_error(display.setMode(100), "INVALID DISPLAY MODE: 100")
    end)
  end)
end)

when I run the specs it errors because of the error in the function. Here's the console output:

$ busted ●●●●✱ 4 successes / 0 failures / 1 error / 0 pending :
0.001444 seconds

Error → test/spec/rom/apis/display_spec.lua @ 32
#API #Display with single monitor should not setMode with invalid mode ./src/rom/apis/display.lua:32: INVALID DISPLAY MODE: 100

stack traceback:    ./src/rom/apis/display.lua:32: in function 'fn'     test/spec/rom/apis/display_spec.lua:34: in function <test/spec/rom/apis/display_spec.lua:32>

It errors with the error I am expecting but the problem is the test should pass, because I am asserting that it is returning the correct error.


Solution

  • You need to wrap the error-making call in a function:

    it("should not setMode with invalid mode", function()
      assert.has_error(function() display.setMode(100) end, "INVALID DISPLAY MODE: 100")
    end)