首页 > 解决方案 > Stubbing a nested function in Jest

问题描述

I have two functions in a module at the module scope. One of the functions is used by another.

async function allCinemas({ puppeteer, states }) {
  const cinemaDetails = [];
  const page = await puppeteer
    .launch({
      handleSIGINT: true /*devtools: false,headless: true*/
    })
    .then(browser => browser.newPage());

  await page.setViewport({ width: 1366, height: 735 }); //form factor - laptop/PC
  await page.goto("https://www.somesite.come");

  for (const state of states) {
    const res = await cinemasfromState(page, state);
    res.forEach(cin => {
      cinemaDetails.push(cin);
    });
  }
  await page.close();

  return cinemaDetails;
}

async function cinemasfromState(page, state) {
  const CINEMA_SELECTOR = `div[$[STATE]] div.top-select-option h.element`;

  let res = await page.evaluate(
    (elementPath, state) => {
      let results = Array.from(document.querySelectorAll(elementPath)).map(
        function(cin, index) {
          let result = {
            cinemaState: this.state,
            cinemaId: cin.getAttribute("id"),
            cinemaName: cin.getAttribute("name"),
          };
          return result;
        },
        { state }
      );

      return  [...results.reduce((a, c) => a.set(c.cinemaId, c), new Map()).values()];     

    },
    CINEMA_SELECTOR.replace("$[STATE]", state),
    state
  );

  return  Promise.resolve(res);
}
export { allCinemas, cinemasfromState };

I have separately tested function cinemasfromState

Therefore when I test function allCinemas, I am thinking of stubbing function cinemasfromState.

How can I not stub/mock cinemasfromState so that I don’t have to duplicate testing?

标签: javascriptunit-testingjestjs

解决方案


利用sinon

在测试b时,您应该测试它对来自a(快乐和失败流)的不同响应的行为。因此,您需要a使用不同的返回来进行存根以b正确测试。

import * as allMethods from './whereever-the-file-is';
import sinon from 'sinon';

// inside your test case
const aStub = sinon.stub(allMethods, 'a');

aStub.returns('x');
// test your function b on what it should do when a returns 'x'

aStub.returns('y');
// test your function b on what it should do when a returns 'y'

我还没有测试过这段代码,所以如果您需要了解更多关于 sinon 存根的信息,请参考官方文档。


推荐阅读