跳至主要内容

示例

你可以在 wyze/bs-dom-testing-library/src/__tests__ 找到更多 bs-dom-testing-library 示例。

你可以在 wyze/bs-react-testing-library/src/__tests__ 找到更多 bs-react-testing-library 示例。

React 测试库

Component_test.re
open Jest;
open Expect;
open ReactTestingLibrary;

test("Component renders", () =>
<div style=ReactDOMRe.Style.make(~color="rebeccapurple", ())>
<h1> {ReasonReact.string("Heading")} </h1>
</div>
|> render
|> container
|> expect
|> toMatchSnapshot
);

DOM 测试库

以下示例使用 bs-webapi 来帮助进行类型化和创建事件。

getByText

__tests__/example_test.re
open Jest;
open DomTestingLibrary;
open Expect;

type parser;

[@bs.new]
external domParser : unit => parser = "DOMParser";

[@bs.send.pipe : parser]
external parseFromString : ( string, [@bs.as "text/html"] _) => Dom.element = "";

[@bs.get]
external body : Dom.element => Dom.element = "";

[@bs.get]
external firstChild : Dom.element => Dom.element = "";

let div = domParser()
|> parseFromString({j|
<div>
<b title="greeting">Hello,</b>
<p data-testid="world"> World!</p>
<input type="text" placeholder="Enter something" />
<input type="text" value="Some value" />
<img src="" alt="Alt text" />
</div>
|j})
|> body
|> firstChild;

describe("getByText", () => {
test("works with string matcher", () => {
let actual = div |> getByText(~matcher=`Str("Hello,"));

expect(actual) |> toMatchSnapshot;
});

test("works with regex matcher", () => {
let actual = div |> getByText(~matcher=`RegExp([%bs.re "/\\w!/"]));

expect(actual) |> toMatchSnapshot;
});

test("works with function matcher", () => {
let matcher = ( _text, node ) => (node |> tagName) === "P";
let actual = div |> getByText(~matcher=`Func(matcher));

expect(actual) |> toMatchSnapshot;
});
});

FireEvent

open Jest;
open DomTestingLibrary;
open Expect;

describe("FireEvent", () => {
test("click works", () => {
open Webapi.Dom;

let node = document |> Document.createElement("button");
let spy = JestJs.inferred_fn();
let fn = spy |> MockJs.fn;
let clickHandler = _ => [@bs] fn("clicked!") |> ignore;

node |> Element.addEventListener("click", clickHandler);

FireEvent.click(node);

expect(spy |> MockJs.calls) |> toEqual([|"clicked!"|]);
});

test("change works", () => {
open Webapi.Dom;

let node = document |> Document.createElement("input");
let spy = JestJs.inferred_fn();
let fn = spy |> MockJs.fn;
let changeHandler = _ => [@bs] fn("changed!") |> ignore;
let event = Event.makeWithOptions("change", { "target": { "value": "1" } });

node |> Element.addEventListener("change", changeHandler);

FireEvent.change(node, event);

expect(spy |> MockJs.calls) |> toEqual([|"changed!"|]);
});
});