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
113 views
in Technique[技术] by (71.8m points)

javascript - How to expect one function to call another function?

I am trying to mock a function call, and expect it to have called another function within it once.

myFunctions.test.js

import { resetModal } from '../myFunctions.js';

describe('resetModal', () => {
  it('calls the clearSomethingInModal function', () => {
    const clearSomethingInModal = jest.fn();
    resetModal();
    expect(clearSomethingInModal.mock.calls.length).toBe(1);
  })
})

myFunctions.js

export resetModal() {
  clearSomethingInModal()
}

However, Jest output says that it has not been called. How can I best do this?

question from:https://stackoverflow.com/questions/40771520/how-to-expect-one-function-to-call-another-function

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

1 Answer

0 votes
by (71.8m points)

Your approach does not work because you mock clearSomethingInModal only in the context of your test file, so clearSomethingInModal in the myFunctions.js is still the original. The main point is that you can't mock something that is directly created in myFunctions.js. The only thing that you can mock are:

  1. Modules that you import to myFunctions.js, like import clearSomethingInModal from 'clearSomethingInModal';
  2. Callbacks that you pass into your function when calling them from your test;

This makes sense if you think about myFunctions.js as a blackbox, where you can control what goes in, like imports or function arguments, and where you can test what comes out. But you can not test the stuff that happens inside the box.

Here are two example that reflect the 2 points in the list:

myFunctions.test.js

import { resetModal } from '../myFunctions.js';
import clearSomethingInModal from 'clearSomethingInModal';

jest.mock('clearSomethingInModal', () => jest.fn())

describe('resetModal', () => {
  it('calls the clearSomethingInModal function', () => {
    resetCreationModal();
    expect(clearSomethingInModal.mock.calls.length).toBe(1);
  })
})

myFunctions.js

import clearSomethingInModal from 'clearSomethingInModal';

export resetModal() {
  clearSomethingInModal()
}

myFunctions.test.js

import { resetModal } from '../myFunctions.js';

describe('resetModal', () => {
  it('calls the clearSomethingInModal function', () => {
    const clearSomethingInModal = jest.fn();
    resetCreationModal(clearSomethingInModal);
    expect(clearSomethingInModal.mock.calls.length).toBe(1);
  })
})

myFunctions.js

export resetModal(clearSomethingInModal) {
  clearSomethingInModal()
}

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

...