Inline tests in rescript


Some tools in the native OCaml world allow to write inline tests, like ppx_inline_test, which in my opinion have a couple of very solid benefits:

  1. colocation of implementation and tests
  2. being able to test functions that are not exported.

Such tools exist in other languages, in Rust for example.

I know @chenglou was working on some testing framework for Rescript, is it a feature you were considering? Is it something that would interest people in the community?


Does this exist in JavaScript, that we could perhaps model a ReScript implementation on?

I like how the educational language Pyret does it:

fun sum(l):
  cases (List) l:
    | empty => 0
    | link(first, rest) => first + sum(rest)
  sum([list: ]) is 0
  sum([list: 1, 2, 3]) is 6

just write a where clause after your function and put the tests in there.

I couldn’t find any equivalent in JS.

What I had in mind was a simple PPX that would not generate anything when building for prod or if it’s a dependency so that it would be 0 cost and inside of which you could use the test framework you want.

1 Like

this is a nice syntax indeed!

Good idea. I like elixir inline tests (in commnets) too.
but it would be tricky in general since it should eval javascript.

Is there a way to avoid shipping the tests when publishing the a module? Also, when do the tests run? Is it on import? Is there any way to disable the tests from running?

I mean, there’s nothing really to stop you from doing this in your source files with your test framework of choice

if (process.env.NODE_ENV === "test") {
  describe("hi", () => {
    it("should be something", () => {

Pretty sure most bundlers would drop it from the module at compile time

1 Like

yes sure, you could also probably use conditional compilation here if you don’t want to use a bundler, but then I guess it means any file can be a test file, which is not ideal, I thought the PPX could also take care of this so we wouldn’t have to point the tests to your whole src folder.

hey, so we decided it was worth it and took a few days to work on a tool that does that and we’re quite happy with the result!

Basically it’s test-framework agnostic solution that allows you do this:

// Math.res
// this function might not even be in Math.resi 
// so impossible to test otherwise
let sum = (a, b) => {
  a + b

// you can use any test framework you like here:
Jest.test("adds 1 + 2 to equal 3", () => {
  expect(sum(1, 2)).toBe(3);

When building for prod, the whole test will be skimmed from the output exactly as you’d want!

This is still beta but please try it and share your feedback if you like what you see!