如何使用Jest模拟和测试Vanilla JS脚本中的函数

时间:2020-07-14 13:15:13

标签: javascript mocking jestjs

我正在尝试使用笑话来测试我的script.js文件,并想查看是否正在调用函数。我正在测试的文件在Vanilla JS中。使用节点js上的端点来加载它们。脚本文件通过下面的index.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();
  });
});

我只想测试是否正在调用该函数。我正在嘲笑它,但似乎无法击中上面的嘲笑功能。实际上,如果我记录了原始函数,则表明该函数已被触发且未调用该模拟。我在这里做错了什么?我正在圈子中,不确定如何正确模拟它。我不知道在此模块中模拟此功能的正确方法。这里的任何帮助将不胜感激!

0 个答案:

没有答案