簡體   English   中英

開玩笑不嘲笑(設置間諜)所需的功能

[英]Jest doesn`t mock(set spy) on needed function

我的測試函數reverseAdd調用了在同一模塊中定義的另一個函數add 我需要測試,如果測試功能調用另一個。

模組

function add(a, b) {
  return a + b;
}

function reverseAdd(a, b) {
  add(b, a);
}

module.exports = {
  add,
  reverseAdd
}

測試

const exp = require('./add');

describe('add', () => {
  it('should add two numbers', () => {
    expect(exp.add(1, 2)).toBe(3);
  });

  it('should add two numbers', () => {
    exp.add = jest.fn();

    exp.reverseAdd();

    expect(exp.add).toHaveBeenCalledTimes(1);
  });
});

結果

Expected mock function to have been called one time, but it was called zero 

據我了解,包裝函數是另一個函數,在測試函數中未調用它。

我如何包裝/間諜功能添加

游樂場: https : //repl.it/repls/WoodenElectricInstances

謝謝@ltamajs,我找到了解決方案

需要重寫模塊到

function add(a, b) {
  return a + b;
}

function reverseAdd(a, b) {
  module.exports.add(b, a); <----- here changes
}

module.exports = {
  add,
  reverseAdd
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM