Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
105 views
in Technique[技术] by (71.8m points)

javascript - How to spy on Node ES6 module function?

In Node 13 & beyond you can import ES modules simply using :

import myModule from './myModule.js'

I decided to use this feature, but quickly I feel like it's not possible to spy function module in my specifications.

I tried implementing it myself, an even using jest or sinon, but none of these allowed me to replace the module function with a "spy wrapper".

My main use case is to determine if consuming module has correctly called consumed module a certain amount of time :

import moduleA from './moduleA.js'
import moduleB from './moduleB.js'
import spy from './spy.js'

function test() {
  const spied = spy(moduleA)
  moduleB()
  return spied.callCount === 3
}

How would you do this ? Preferably without framework. Libraries are allowed ;)

import sinon from 'sinon'
import { FEATURE } from "../../spec-section/_enums/type/spec-section.type.enum.js";
import build from './build.js'
import websitePageBuild from '../../website-page/build/build.js'
import websiteFolderMotif from "../website-folder.motif.js";
import websitePageMotif from "../../website-page/website-page.motif.js";

/** I'm exporting my test object to be ran by my specification framework
 * (aggregates all `.spec.js` file and `await` for each of them to resolve). */
export default {
  type: FEATURE,
  label: 'For each WEBISTE_PAGE in content, '
    + 'the WEBSITE_PAGE `build` should be call once.',
  test: async () => {
    const spy = sinon.spy(websitePageBuild)
    await build(
      'fr',
      /** Website tree description. 
       * This very instance owns four page. */
      {
        name,
        websiteFolderMotif.shape({
          '': websitePageMotif.shape(() => '', {}),
          'about': websitePageMotif.shape(() => '', {}),
          'articles': websiteFolderMotif.shape({
            1: websitePageMotif.shape(() => '', {}),
            2: websitePageMotif.shape(() => '', {}) 
          })
        }})
    /** But call count remains 0. */
    const callCount = spy.callCount
    return callCount === 4
  }
question from:https://stackoverflow.com/questions/65859071/how-to-spy-on-node-es6-module-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...