Как имитировать и тестировать функции в ванильном JS скрипте с помощью jest - PullRequest
0 голосов
/ 14 июля 2020

Я пытаюсь протестировать свой файл script. js с помощью шутки и хочу узнать, вызывается ли функция. Файлы, которые я тестирую, имеют ванильный JS. Они загружаются с помощью конечной точки на node js. Файл сценария загружается через индекс. html ниже:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Pokedex</title>
    <!-- <link rel="icon" href="/favicon.ico"> -->
    <link rel="stylesheet" href="main.css" />
    <meta name="description" content="Pokedex" />
  </head>
  <body>
    <h1>Our Pokedex!</h1>
    <section>
      <div class="entry-container">
        <div class="search-box">
          <form class="" action="" method="" id="the-form">
            <h2>Search for your pokemon</h2>
            <div class="input-box">
              <input type="text" id="poke-input" required="" autofocus />
              <label for="poke-input">Enter Pokemon Here</label>
            </div>
          </form>
          <div id="output"></div>
        </div>
      </div>
    </section>
    <script src="script.js"></script>
  </body>
</html>

Сценарий для этого файла:

const pokeinput = document.getElementById("poke-input");
pokeinput.addEventListener("keyup", () => {
  fetch(`/search/${pokeinput.value}`)
    .then((response) => {
      /* TODO: create /search endpoint which fetches our text file, and compares it to our query
      which is given by our endpoint which is created by input.value */
      return response.text();
    })
    .then((data) => {
      showResults(data);
    })
    .catch((error) => {
      console.error("Error:", error);
    });
});

function showResults(searchOutput) {
  const results = document.getElementById("output");
  if (searchOutput.length == 0) {
    results.innerText = "No Results Found";
  } else {
    results.innerHTML = searchOutput;
  }
}

Я пытаюсь проверить, работает ли функция showResults вызывается выше.

/**
 * @jest-environment jsdom
 */
//
const supertest = require("supertest");
// const testingLib = require("@testing-library/dom");
const fetchMock = require("fetch-mock");
const fs = require("fs");
const path = require("path");
// To add html do the following:
// Suggested from https://dev.to/snowleo208/things-i-learned-after-writing-tests-for-js-and-html-page-4lja
const html = fs.readFileSync(path.resolve(__dirname, "./index.html"), "utf8");
document.documentElement.innerHTML = html.toString();
const script = require("./script");
jest.mock("./script", () =>
  Object.assign({}, jest.requireActual("./script"), {
    showResults: jest.fn(),
  })
);

describe("searchPokedex tests", () => {
  beforeAll(() => {
    fetchMock.restore();
  });
  it("should take in string", async () => {
    const pokeinput = document.getElementById("poke-input");
    fetchMock.getOnce("begin:/search", {
      status: 200,
      body: "Yamask",
    });

    await pokeinput.dispatchEvent(new KeyboardEvent("keyup", { key: "y" }));
    // const results = document.getElementById("output");
    // await testingLib.waitFor(() => expect(results.innerHTML).toBe("Yamask"));
    expect(script.showResults).toHaveBeenCalled();
  });
});

Я хочу просто проверить, вызывается ли функция. Я издеваюсь над этим, и мне кажется, что я не могу использовать издеваемую функцию выше. Фактически, если я регистрирую исходную функцию, она показывает, что она запускается, а макет не вызывается. Что я здесь делаю не так? Я хожу по кругу и не знаю, как правильно над этим издеваться. Я не знаю, как правильно издеваться над этой функцией в модуле. Любая помощь здесь будет оценена!

...