在Jest中插入嵌套函数

时间:2018-11-12 04:36:32

标签: javascript unit-testing jestjs

我在模块作用域的模块中有两个功能。其中一个功能被另一个使用。

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 };

我已经分别测试过function cinemasfromState

因此,当我测试function allCinemas时,我正在考虑存根function cinemasfromState

我如何不存根/模拟cinemasfromState以便不必重复测试?

2 个答案:

答案 0 :(得分:1)

使用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存根的信息,请参考official docs

答案 1 :(得分:0)

只要两个函数都在同一个模块中定义,就没有一种明智的方式来模拟仅一个函数,然后另一个函数使用该模块。也许很清楚为什么要考虑执行代码的顺序。

  1. 在模块内部声明了两个功能AB。函数B引用了函数A
  2. 该模块已导入您的测试中。目前无法在A内部删除对B的引用。

因此,要模拟这两个功能的唯一方法就是将它们放在不同的模块中,因为您可以在测试中轻松模拟其中的一个。导出它们时,将它们放在不同的模块中应该很容易。

相关问题