Giter VIP home page Giter VIP logo

rescript-jest's People

Contributors

actionshrimp avatar alliannas avatar arnarthor avatar carlolson avatar chenglou avatar czystyl avatar dependabot[bot] avatar glennsl avatar ijcd avatar jihchi avatar jmuhlich avatar kiranps avatar logangrier avatar lyleg avatar makoru-hikage avatar nrako avatar qziem avatar renovatorruler avatar sacarr avatar superherointj avatar tryggvigy avatar wtfleming avatar zploskey avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rescript-jest's Issues

Add an example with testPromise function

HI guys, Thanks for this porting.
I m very new to ReasonML I m able to run the unit test with jest, but I can't make it work with promises.
Could you add an example in the docs with an example of testPromise?

Figure out how to support `new` invocations of mock function.

This is the use case in jest proper:

const mockFn = jest.fn();
const instance = new mockFn();

mockFn is not just a function, but also has a number of properties and methods. To be able to call it as a function in bs, there is a Mock.fn function (implemented as external fn : ('fn, _, _) fn -> 'fn = "%identity") that's used like this:

let mockFn = Jest.fn () in
let fn = Mock.fn mockFn in
let ret = fn ()

A new invocation would likely need to follow a similar pattern, but is it possible to do? Or could it be made possible?

I've tried to solve it with a %bs.raw function, but that of course results in the lovely error about types that cannot be generalized:

    let make : ('fn, _, _) fn -> 'fn = [%bs.raw {|
      function(self) {
        return new (Function.prototype.bind.apply(self, arguments));
      }
    |}]

cc @bobzhang

How to test that a promise was rejected?

I'm using bs-knex to write to postgres, and have set up a unique constraint on an email column.
I would like to write a test to ensure a promise is rejected if someone attempts to create a user with an existing email.
I came up with the following simplified example, that sort of works (the test passes and would fail if changed so that the email addresses were not the same), but isn't ideal.

  testPromise("An email address is unique", () =>
    Database.insert(~email="[email protected]")
    |> Js.Promise.then_(_ =>
         Database.insert(~email="[email protected]")
       )
    |> Js.Promise.catch(_ => {
         /* If this catch block doesn't get reached, a user will be returned from the function and the test will fail when run. */
         /* If we do get here, need to return a passing assertion for the test to pass */
         /* Also todo, would want to ensure the error message is along the lines of "That email address is already in use."*/
         let assertion = expect(1) |> toBe(1);
         Js.Promise.resolve(assertion);
       })
  );

Is this possible with bs-jest? Or am I approaching this the wrong and there a better way I could be approaching this?

Expose assertion constructors (test a test library)

I am building a testing library for a particular task on top of Jest. I want to make sure my tests are returning the correct assertions. The way I was thinking of doing it was make sure it matches things like Just Ok and Just (Fail message) but that would require those types being exposed.

Snapshot removed by bucklescript -clean-world

When I run bsb -clean-world all files inside lib/ directory will be removed (including .snap file generated by jest). This means I can't do clean + build + test on CI because the snapshot is removed and jest won't create new snapshot on CI (as it should).

Do you have suggestion how to handle this? For now I'm only running build + test on CI. Or is that the recommended approach?

ReferenceError: describe is not defined

The describe function is not being imported properly from the Jest module. For some reason, the generated JS code does not append the Jest prefix, so somehow it's considered to be globally available.

However, after hand-modifying the code to use Jest.describe instead of just describe, the function is still undefined.

Somehow, the describe function is not getting imported, or perhaps the compiled JS code does not even define it in the library.

I am currently using bs-platform version 7.0.1. I would be happy to supply examples if necessary.

Consider matching underlying Jest version

A recent patch-version change to bs-jest bumped the underlying jest dependency to a new major version, which caused our tests to break (due to some weird babel version issues that I still haven't quite figured out).

I realize bs-jest is a bit more than a wrapper around Jest, but would it make sense to adopt a versioning strategy that matches the underlying Jest version?

Multiple assertions in specified order

Hi. I am looking into porting some API-tests written in F# from our backend to OCaml/Bucklescript. I've read the documentation part about all tests having to return an assertion, which forces to have one and only one assertion, so I am wondering whether it's possible to achieve such an imperative testing scenario with bs-jest at all. So far, I have managed to make one API call and make one assertion on the result, but have no idea how I would go about chaining another API call using the ID returned by the first one and making another assertion.
Here is my simple attempt with one assertion:

testPromise "getResources should return 20 resources" (fun () ->
  getResources "url"
    |> Js.Promise.then_ (fun res ->
      expect (res |. Belt.Array.length) |> toBe 20 |> Js.Promise.resolve
    )
);

Here is a sample F#/xUnit test I am trying to convert:

[<Fact>]
let ``Sample test for adding and removing a resource`` () : unit =
    let createResponse = createRandomResource ()

    getAllResources()
    |> List.map (fun i -> i.Id)
    |> should contain createResponse.Id // First assertion

    deleteResource createResponse.Id  // Using the ID from the first response

    getAllResources ()
    |> List.map (fun i -> i.Id)
    |> should not' (contain createResponse.Id)  // Second assertion

Writing such a test with TypeScript and async/await is pretty much straightforward.

Is Expect extensible?

Hello, thanks for the bindings!
I've looked into the code and as far as I can see, the Expect module creates jest assertions via assertion variant. This makes the API clean, but doesn't really allow users to introduce custom matchers. E.g. we use jest-dom and testing-library/jest-native and we weren't been able to properly cooperate the custom matchers with Expect module.

Skip.testPromise sets test name to undefined

Skip.testPromise("can get a model and train it", () => {
    ...
});

compiles to

it.skip(undefined, "can get a model and train it", (function () {}))

Which throws

Invalid first argument, undefined. It must be a string.

Support for "esbuild-jest"

This is for projects using React which requires es6 builds. React projects typically uses ES6 builds.

Error when importing image

I'm getting an error when trying to run tests that contain code that imports an image. Building & running the app works fine, I only get the error when running the tests.

client/img/logo.png:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){�PNG
                                                                                             ^

    SyntaxError: Invalid or unexpected token

      2 | 'use strict';
      3 |
    > 4 |
        | ^
      5 | var logo = (require("../../img/logo.png"));
      6 |
      7 | exports.logo = logo;

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
      at Object.<anonymous> (src/shared/Images.bs.js:4:12)

Is this something related to bs-jest?

Decide on the shape of the expect/assertion API

See https://github.com/BuckleTypes/bs-jest/blob/master/__tests__/expect_test.ml for the contestants.

Currently expect (1 + 2) |> toBe 3 (Expect1) is winning because:

  • It's most familiar to existing jest users
  • It most closely matches the output of the test runner
  • It reads fluently
  • It clearly differentiates between expected and actual values
  • It's among the most flexible (can even do expect (1 + 2) = 3 with just 6 or so warnings!)

Runner up: Assert.(1 + 2 |> toBe 3)

Only the result of the final expectation is used

I am seeing an issue when using multiple expectations in a single test. If the final expectation succeeds then the test passes, regardless of the outcome of the others. E.g.

    testOnly "sums numbers" (fun () => {
      expect (1 + 2) |> toEqual (3);
      expect (1 + 2) |> toEqual (4);
    });

correctly fails the test, but

    testOnly "sums numbers" (fun () => {
      expect (1 + 2) |> toEqual (4);
      expect (1 + 2) |> toEqual (3);
    });

incorrectly passes the test.

If I have time I will investigate further...

Mismatch between Jest's test() and bs-jest's test()

It seems that in the original Jest API, the global test() method documented here does not need to return anything, it's a void method.

However, in bs-jest it seems the API is a little different:

val test : string -> (unit -> assertion) -> unit
val testAsync : string -> ((assertion -> unit) -> unit) -> unit
val testPromise : string -> (unit -> assertion Js.Promise.t) -> unit
val testAll : string -> 'a list -> ('a -> assertion) -> unit

The function passed to the test function is of type unit -> assertion whereas I would expect it to be unit -> unit. Is there any particular reason for this? My problem here stems from the fact that one test() invocation might have various expect calls. Which assertion should that invocation return?

Expect method not_ is not bound?

Telling me: not_ and toThrow are not bound, while toEqual is bound.
What am I doing wrong? Please update the tests included to follow latest syntax and provide better docs to get started, using bs-platform 4.0.x, migrating from Jest in JavaScript land. Thanks :)

Error: Unbound value not__
Hint: Did you mean not_?

But why is it complaining about not__ when I clearly wrote not_ in the code? Makes no sense

I'm trying to make a simple binding of html method in lit-html following this [binding tutorial](https://itnext.io/reasonml-create-bindings-for-npm-package-b8a3c6d0703e

src/LitHtml.re

[@bs.module "LitHtml"] [@bs.val]
external html: string => Js.nullable(string) = "html";
let html = htmlStr => html(htmlStr) |> Js.Nullable.toOption;

Tests

open Jest;

let write = () => LitHtml.html("<div></div>")

open Expect;

describe("LitHtml", () =>
  test("#html", () =>
    expect(() => write()) |> not_ |> toThrow
  )
);

describe("Calc", () =>
  test("#add", () =>
    expect(1 + 1) |> toEqual(1)
  )
);

I tried all kinds of combinations with Expect but so far to no avail.

Posted the question on Stackoverflow as well

Mention way to put tests in components

I was thinking about it, and there should probably be a way to put tests in components. I like the architecture wherein I can add tests within the component so everything can be contained within.

Issue with mocking?

I've tried to mock the node os module for testing

open Jest;
open Expect;

JestJs.mockWithFactory("os", () =>
  {"userInfo": () => {"username": "jest"}, "platform": () => "darwin"}
);

describe("Util", () =>
  describe("getSublimeTextPackageDir", () =>
    test("should return the macOS path", () =>
      expect(Util.getSublimeTextPackageDir())
      |> toBe(
           "/Users/jest/Library/Application Support/Sublime Text 3/Packages/",
         )
    )
  )
);

When i move the Mock within the test or describe block, It doesn't work at all. Do I need to use spyOn here?

Expected substring `RE_EXN_ID`

I was updating this repo on this fork -> https://github.com/idkjs/rebase/tree/reason and got the following errors when I ran the tests. It would seem that the expected response was correct but the formatting was wrong. I thought it might be a snapshot thing but I cant find any in the repo.

I guess it has to do with what is being passed to Jest.assertion:

On toThrow, the expected substring has to fields an is escaped. The recieved value has three fields and is not escaped. So the second value looks correct but it not being decoded right?

    Expected substring: "{\"RE_EXN_ID\":\"Rebase__Types.InvalidArgument/4\",\"_1\":\"\"}"
    Received value:     {"Error": [Error], "RE_EXN_ID": "Rebase__Types.InvalidArgument/4", "_1": "Array.range: ~step=0 would cause infinite loop"}

How would I address fixing this issue?

FAIL  __tests__/Seq_test.bs.js
  ● range - step 0

    expect(received).toThrow(expected)

    Expected substring: "{\"RE_EXN_ID\":\"Rebase__Types.InvalidArgument/4\",\"_1\":\"\"}"
    Received value:     {"Error": [Error], "RE_EXN_ID": "Rebase__Types.InvalidArgument/4", "_1": "Seq.range: ~step=0 would cause infinite loop"}

      at affirm (node_modules/@glennsl/bs-jest/src/jest.bs.js:153:38)
      at Object.<anonymous> (node_modules/@glennsl/bs-jest/src/jest.bs.js:238:11)

 FAIL  __tests__/Option_test.bs.js
  ● getOrRaise - None

    expect(received).toThrow(expected)

    Expected substring: "{\"RE_EXN_ID\":\"Rebase__Types.InvalidArgument/4\",\"_1\":\"getOrRaise called on None\"}"
    Received value:     {"Error": [Error], "RE_EXN_ID": "Rebase__Types.InvalidArgument/4", "_1": "getOrRaise called on None"}

      at affirm (node_modules/@glennsl/bs-jest/src/jest.bs.js:153:38)
      at Object.<anonymous> (node_modules/@glennsl/bs-jest/src/jest.bs.js:238:11)

 FAIL  __tests__/Result_test.bs.js
  ● wrap - Error

    expect(received).toEqual(expected) // deep equality

    - Expected  - 0
    + Received  + 1

      Object {
        "TAG": 1,
        "_0": Object {
    +     "Error": [Error],
          "RE_EXN_ID": "Failure",
          "_1": "err",
        },
      }

      at affirm (node_modules/@glennsl/bs-jest/src/jest.bs.js:82:38)
      at Object.<anonymous> (node_modules/@glennsl/bs-jest/src/jest.bs.js:238:11)

  ● wrap1 - Error

    expect(received).toEqual(expected) // deep equality

    - Expected  - 0
    + Received  + 1

      Object {
        "TAG": 1,
        "_0": Object {
    +     "Error": [Error],
          "RE_EXN_ID": "Failure",
          "_1": "err",
        },
      }

      at affirm (node_modules/@glennsl/bs-jest/src/jest.bs.js:82:38)
      at Object.<anonymous> (node_modules/@glennsl/bs-jest/src/jest.bs.js:238:11)

  ● wrap2 - Error

    expect(received).toEqual(expected) // deep equality

    - Expected  - 0
    + Received  + 1

      Object {
        "TAG": 1,
        "_0": Object {
    +     "Error": [Error],
          "RE_EXN_ID": "Failure",
          "_1": "err",
        },
      }

      at affirm (node_modules/@glennsl/bs-jest/src/jest.bs.js:82:38)
      at Object.<anonymous> (node_modules/@glennsl/bs-jest/src/jest.bs.js:238:11)

  ● getOrRaise - Error

    expect(received).toThrow(expected)

    Expected substring: "{\"RE_EXN_ID\":\"Rebase__Types.InvalidArgument/4\",\"_1\":\"getOrRaise called on Error\"}"
    Received value:     {"Error": [Error], "RE_EXN_ID": "Rebase__Types.InvalidArgument/4", "_1": "getOrRaise called on Error"}

      at affirm (node_modules/@glennsl/bs-jest/src/jest.bs.js:153:38)
      at Object.<anonymous> (node_modules/@glennsl/bs-jest/src/jest.bs.js:238:11)

 PASS  __tests__/Fn_test.bs.js
 FAIL  __tests__/List_test.bs.js
  ● range - step 0

    expect(received).toThrow(expected)

    Expected substring: "{\"RE_EXN_ID\":\"Rebase__Types.InvalidArgument/4\",\"_1\":\"\"}"
    Received value:     {"Error": [Error], "RE_EXN_ID": "Rebase__Types.InvalidArgument/4", "_1": "List.range: ~step=0 would cause infinite loop"}

      at affirm (node_modules/@glennsl/bs-jest/src/jest.bs.js:153:38)
      at Object.<anonymous> (node_modules/@glennsl/bs-jest/src/jest.bs.js:238:11)

 PASS  __tests__/ReasonSyntax_test.bs.js
 FAIL  __tests__/Array_test.bs.js
  ● range - step 0

    expect(received).toThrow(expected)

    Expected substring: "{\"RE_EXN_ID\":\"Rebase__Types.InvalidArgument/4\",\"_1\":\"\"}"
    Received value:     {"Error": [Error], "RE_EXN_ID": "Rebase__Types.InvalidArgument/4", "_1": "Array.range: ~step=0 would cause infinite loop"}

      at affirm (node_modules/@glennsl/bs-jest/src/jest.bs.js:153:38)
      at Object.<anonymous> (node_modules/@glennsl/bs-jest/src/jest.bs.js:238:11)

  ● getOrRaise - out of bounds

    expect(received).toThrow(expected)

    Expected substring: "{\"RE_EXN_ID\":\"Rebase__Types.IndexOutOfBounds/5\"}"
    Received value:     {"Error": [Error], "RE_EXN_ID": "Rebase__Types.IndexOutOfBounds/5"}

      at affirm (node_modules/@glennsl/bs-jest/src/jest.bs.js:153:38)
      at Object.<anonymous> (node_modules/@glennsl/bs-jest/src/jest.bs.js:238:11)

  ● setOrRaise - out of bounds

    expect(received).toThrow(expected)

    Expected substring: "{\"RE_EXN_ID\":\"Rebase__Types.IndexOutOfBounds/5\"}"
    Received value:     {"Error": [Error], "RE_EXN_ID": "Rebase__Types.IndexOutOfBounds/5"}

      at affirm (node_modules/@glennsl/bs-jest/src/jest.bs.js:153:38)
      at Object.<anonymous> (node_modules/@glennsl/bs-jest/src/jest.bs.js:238:11)

-----------------------|---------|----------|---------|---------|-------------------
File                   | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------------------|---------|----------|---------|---------|-------------------
All files              |     100 |      100 |     100 |     100 |
 __tests__/helpers     |     100 |      100 |     100 |     100 |
  TestHelpers.bs.js    |     100 |      100 |     100 |     100 |
 src                   |     100 |      100 |     100 |     100 |
  Rebase.bs.js         |     100 |      100 |     100 |     100 |
  Rebase__Array.bs.js  |     100 |      100 |     100 |     100 |
  Rebase__Fn.bs.js     |     100 |      100 |     100 |     100 |
  Rebase__List.bs.js   |     100 |      100 |     100 |     100 |
  Rebase__Option.bs.js |     100 |      100 |     100 |     100 |
  Rebase__Result.bs.js |     100 |      100 |     100 |     100 |
  Rebase__Seq.bs.js    |     100 |      100 |     100 |     100 |
  Rebase__String.bs.js |     100 |      100 |     100 |     100 |
  Rebase__Types.bs.js  |     100 |      100 |     100 |     100 |
-----------------------|---------|----------|---------|---------|-------------------
Test Suites: 5 failed, 3 passed, 8 total
Tests:       10 failed, 323 passed, 333 total
Snapshots:   0 total
Time:        4.746 s
Ran all test suites.

Thank you,sir.

Access to methods not-exposed in module interface

Hello! Is it possible for bs-jest to test functions of a module that are not exposed in the module's interface? I've written a small utility library with a number of private methods that should not be a part of it's public API, so I defined a rei file just with the public portions. But now I can't seem to write unit tests against these private functions.

Publish to npm

Could you please publish this to npm? So I can incorporate this into bs-containers. Thanks!

Doesn't work with bs-platform 4.0.7

I'm trying to upgrade to the latest bs-platform, but this breaks all of my Jest tests.

  ✕ renders (5025ms)

  ● renders

    Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.

       7 | var ReactShallowRenderer = require("bs-react-test-renderer/src/ReactShallowRenderer.bs.js");
       8 |
    >  9 | Jest.test("renders", (function (param) {
         |      ^
      10 |         var component = ReactShallowRenderer.renderWithRenderer(ReasonReact.element(undefined, undefined, FourOhFour.make(/* array */[])));
      11 |         return Jest.Expect[/* toMatchSnapshot */16](Jest.Expect[/* expect */0](component));
      12 |       }));

      at Spec (node_modules/jest-jasmine2/build/jasmine/Spec.js:85:20)
      at Object.test$1 [as test] (node_modules/@glennsl/bs-jest/src/jest.js:248:3)
      at Object.test (src/components/__tests__/fourOhFour_test.bs.js:9:6)

fourOhFour_test.re

open Jest;

open Expect;

test("renders", _ => {
  let component = <FourOhFour /> |> ReactShallowRenderer.renderWithRenderer;
  expect(Js.Undefined.return(component)) |> toMatchSnapshot;
});

fourOhFour.re

let component = ReasonReact.statelessComponent("404");

let make = _children => {...component, render: _self => <div> <h1> {ReasonReact.string("404")} </h1> </div>};

Please update tests to latest ReasonML syntax

Trying to learn how to write tests using the tests in this project. Not sure what other resources to use.
Currently trying to write bindings for lit-html, but getting stuck trying to write a simple test.

bs-jest could help us fix a mistake.

We introduced a subtle breaking change which we thought would be very rare, but turns out it's not so rare.

Previously in Reason, ! parsed as not and not also parsed as not.
Now in Reason, ! parses as not and not parses as not_ and not_ parses as not__.

This breaks some users of bs-jest, and it's Reason's fault.
But instead of a very painful fix on Reason's end, maybe bs-jest could help us out since it's the main user of not_. If bs-jest were to add a duplicate export of not_ (add the export named not__) then everything would be fixed.

What do you think, @glennsl?

Sorry for the trouble.

Add `describeAll` ?

I can currently generate and run a list of test suites with:

Belt.List.forEach(
  ["a", "b", "c"],
  data =>
  describe("a suite", () => {
     /* tests here */
  })
);

Would it be possible to add a shortcut describeAll function like the following?

describeAll("description", ["a", "b", "c"], data => {
  /* tests here */
});

Support for composite asserts

This is pseudo code illustrating the use case (api test)

describe("Authentication service", () => 
  testPromise("Should save user", ()=> {
    let requestResult = client->ServiceClient.saveUser(...)
    let savedUser = // retrieve saved user
         
    expect(requestResult) |> toBe(...)  
    && expect(savedUser) |> toBe(savedUser) 
    });
});

Examples of tests written in BuckleScript

When I was getting started using this binding, I immediately ran into issues. Yes, the bindings try to follow Jest's original API which is well documented. But, there are SOME differences that present speed-bumps for new adopters. Yes, there are tests and I really want to thank whoever took the time to write them. But the documentation they provide is not always helpful because the descriptions are not very descriptive. I would appreciate some examples in the readme.md for the following:

  • Normal Tests
  • Async Tests
  • Promise Tests
  • Only
  • BeforeAll, BeforeAllPromise, BeforeAllAsync
  • AfterAll, AfterAllPromise, AfterAllAsync
  • ... and the mocking/stubbing functionality that I haven't been able to dig into yet.

Implementation of `toBeCalled` and related functions

Thanks for putting together these bindings to Jest.

Have you ruled out accepting a PR with bindings for Jest Expect's toBeCalled and related functions? It's not clear to me based on prior issues and the Not implemented comments in the source. Thanks in advance for your clarification.

possibility of pipe-first version?

Would it be possible to create a pipe-first version of the library? - Or, is there a reason why pipe-last works better in the expect chain?

I'm asking this as someone who is only developing in Rescript for 4 months. Plain interest, as it seems to me that pipe-first is preferred in Rescript for most uses.

Also, thanks for the library! It works great for me.

Jest 25

Jest released 25 version. This library has dependency to jest 24. Good to upgrade it, or maybe it should be moved to peerDependency?

Tests failing on download

Downloading the package, running npm install and then npm run test causes the following error:

[1/1] Building __tests__/reason_syntax_test.cmj

  We've found a bug for you!
  /home/matt/development/bs-jest/__tests__/reason_syntax_test.re 12:24-26
  
  10 ┆ 
  11 ┆ test("not toBe", () =>
  12 ┆     expect(1 + 2) |> not |> toBe(4));
  13 ┆ 
  14 ┆ test("not_ toBe", () =>
  
  This has type:
    bool => bool
  But somewhere wanted:
    Jest.Expect.plainPartial(int) => 'a
  
  The incompatible parts:
    bool
    vs
    Jest.Expect.plainPartial(int) (defined as [ `Just(int) ])
  
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! @glennsl/[email protected] build: `bsb -make-world`
npm ERR! Exit status 2
npm ERR! 
npm ERR! Failed at the @glennsl/[email protected] build script.

The flags on Github show builds as passing though...

expectation that uses pattern matching?

I am not sure exactly how this would be implemented or whether there is already something in the api that can express this, but I love scalatest's inside matcher. If you like it as well, consider adding something similar eventually.

Thanks for this library. It has been a pleasure to use so far and the discussion of es6 was also helpful.

return statement in describe callback throwing warning

I am getting this warning:

 A "describe" callback must not return a value.
 Returning a value from "describe" will fail the test in a future version of Jest.

I am new to Jest so if there is an obvious work around let me know.

The issue is that compiled function from Reason always has a return statement, and Jest does not like the callback in describe returning something. This is not a big issue right now, as it just a warning and tests actually pass.

Support for end-to-end tests...

Hi,

Firstly, I've just found bs-jest, I've just started using it for unit tests and its great, so thank you for that. The problem is now I'd really like to use it for end-to-end tests...

Some background:

  • I've got a Reason React Native mobile app with some end-to-end tests written in detox, which is working really nicely.
  • Detox tests currently have to be written in javascript and I'd obviously much rather write them in reasonml.

Detox uses jest under the hood and I'm thinking it would be awesome if there was a way to write Detox tests in bs-jest.

I am mindful of bs-jest's stance of one assertion per test, which I completely agree with for unit tests, but in my experience end-to-end tests are always going to be more imperative by nature (i.e. type some things in, click a button, assert some things, do the next thing, assert some more things etc).

I'm wondering if you think there might be away to integrate the two, or perhaps have some way to extend bs-jest to support Detox?

Many thanks,
Paul

How would addSnapshotSerializer fit in bs-jest?

Hey @glennsl

I was trying to add the "binding" to expect.addSnapshotSerializer() in bs-jest and I found creating too much crap for this particular case.

How it works it's simple, while expect.extend adds prototype methods to the matches, expect.addSnapshotSerializer adds transformations to the snapshots and both methods are called once on top of the file (or in any setup.js file)

That's a valid serializer:

const serializer = {
	test: () => true
	print: (value) => JSON.stringify(value)
}

expect.addSnapshotSerializer(serializer);

So, a serializer it's a

type serializer = <
  test :value -> bool;
  print :value -> serialize -> indent -> string
> Js.t

But I end up adding addSnapshotSerializer to the prototype with the affirm. Would you mind some advice on how to add it without too much hassle?

Thanks!

Received: serializes to the same string on object equality checking

When testing something that returns this type

type containsText =
  | ArrivedWithString(string);

like the following

      expect(myFunction(aGADT))
      |> toBe(Some(ArrivedWithString("hello")))

we get an error

    expect(received).toBe(expected) // Object.is equality

    If it should pass with deep equality, replace "toBe" with "toStrictEqual"

    Expected: ["hello"]
    Received: serializes to the same string

      at affirm (node_modules/@glennsl/bs-jest/src/jest.js:72:40)
      at Object.<anonymous> (node_modules/@glennsl/bs-jest/src/jest.js:249:11)

If we print the object result we get that it is:
[ 'hello' ]
It is a bit unclear what is meant by "serializes to the same string". That they are different but serialize to the same thing?

Add assertion combinators

There is a lot of cases where I want to write something like this:

        test "Barray.set" (fun () ->
            let arr = [|1; 2; 3|] in
            let b = Barray.set 1 3 arr in
            Expect.toEqual b true `and` Expect.toEqual arr [|1; 3; 3|]
        );

So we can combine two assertions into one. Do you think this is possible? @glennsl

Thanks!

Eliminate `Mock.mock`

Mock.mock is just a stopping point on the way to Mock.instances and Mock.calls. This is made worse by mockClear replacing the object returned by Mock.mock, making it unsafe to store the result of Mock.mock in a temporary variable.

This would all be solved if it was possible to define externals like this:

external calls : ('args, _) mock -> 'args array = "mock.calls" [@@bs.get]

But this results in the error "Not a valid name mock.calls". Is there a better way to do this, or could this be made possible @bobzhang ?

Handle toHaveBeenCalled

Good to write bindings for toHaveBeenCalled, toHaveBeenCalledWith,... and other methods for mock functions.

Problem with es6 modules

Hi!
I have small problem with bs-jest.

In my bsconfig.json I have es6 modules:

  "package-specs": {
    "module": "es6",
    "in-source": true
  },

When I run tests, it gives me the error like below:

$ jest
 FAIL  __tests__/Template_test.bs.js
  ● Test suite failed to run

    ....../node_modules/@glennsl/bs-jest/src/jest.js:3
    import * as List from "bs-platform/lib/es6/list.js";
    ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      1 | // Generated by BUCKLESCRIPT, PLEASE EDIT WITH CARE
      2 | 
    > 3 | import * as Jest from "@glennsl/bs-jest/src/jest.js";
        | ^
      4 | 
      5 | Jest.describe("TestSuite", (function (param) {
      6 |         return Jest.test("test", (function (param) {

      at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:537:17)
      at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:579:25)
      at Object.<anonymous> (__tests__/Template_test.bs.js:3:1)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        0.468s, estimated 2s
Ran all test suites.

When I change module to commonjs, everything starts working. (I can't do this permamently, because I have own bindings, that not compatible with commonjs)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.