mockth

Types

pub type History {
  History(
    pid: Pid,
    module: String,
    function: String,
    arguments: List(Dynamic),
  )
}

Constructors

  • History(
      pid: Pid,
      module: String,
      function: String,
      arguments: List(Dynamic),
    )

    Module, function and arguments that the mock module got called with.

Functions

pub fn expect(
  module module: String,
  function function: String,
  with fun: a,
) -> Result(Bool, String)

Mock a function. The function fun should return the value that the function will return when called.

pub fn expect1_test() {
 let assert Ok(_) =
   mockth.expect("gleam@function", "identity", fn(_) { "hello" })

 mockth.validate("gleam@function")
 |> should.equal(True)

 mockth.mocked()
 |> should.equal(["gleam@function"])

 function.identity("world")
 |> should.equal("hello")
}
pub fn history(module: String) -> Result(List(History), String)

Returns the history of calls to the mocked module. Dont support exception handling.

pub fn mocked() -> List(String)

Returns the currently mocked modules.

pub fn unload(module: String) -> Result(Bool, String)

Unload a mocked module or a list of mocked modules. This will purge and delete the module(s) from the Erlang virtual machine. If the mocked module(s) replaced an existing module, this module will still be in the Erlang load path and can be loaded manually or when called.

pub fn unload_all() -> List(String)

The function returns the list of mocked modules that were unloaded in the process. Unloads all mocked modules from memory.

pub fn validate(module: String) -> Bool

Validate the state of the mock module(s). Validation can detect:

  • When a function was called with the wrong argument types (function_clause)
  • When an exception was thrown
  • When an exception was thrown and expected (via meck:exception/2), which still results in true being returned

Validation cannot detect:

  • When you didn’t call a function
  • When you called a function with the wrong number of arguments (undef)
  • When you called an undefined function (undef)
pub fn with_mock(
  module module: String,
  function function: String,
  replacement fun: a,
  testcase f: fn(String) -> b,
) -> List(String)

Utility function to set up mocks with the use sugar.

 pub fn with_mock_test() {
  use mock <- mockth.with_mock(
    module: "gleam@function",
    function: "identity",
    replacement: fn(_) { "hello" },
  )

  function.identity("world")
  |> should.equal("hello")

  // the mocked module is available here as `mocks`
  // for example to be able to call `mockth.history` with it.
}
Search Document