代码之家  ›  专栏  ›  技术社区  ›  zilijonas

jest-测试一个函数是否调用另一个函数

  •  0
  • zilijonas  · 技术社区  · 6 年前

    我有一个包含一些静态函数的类。我们把这个类称为allfunctions。allfunctions.makechanges(a,b,c)调用allfunctions.callUpdate()。

    这些函数都不返回任何值。它们都只是修改一些参数并调用一个提供这些参数的函数。

    export class allFunctions {
    
        public static makeChanges(a, b, c) {
            ...
            this.callUpdate(c, d);
        }
    
        public static callUpdate(c, d) {
            otherFunctions.makeUpdate();
        }
    
    }
    

    如果调用callUpdate()函数,我想测试何时调用函数makechanges()。

    我试过这样的方法:

    import { allFunctions } from '../allFunctions';
    
    describe('simple test', () => {
    
        it('makeChanges() should call callUpdate()', () => {
    
            const a = 1, b = 2, ...;
    
            allFunctions.callUpdate = jest.fn();
    
            const result = allFunctions.makeChanges(a,b,c);
    
            expect(allFunctions.callUpdate).toBeCalled();
    
        });
    
    });
    

    可悲的是,这行不通。是否可以测试一个函数是否调用另一个函数?如果是这样,最好的方法是什么?

    2 回复  |  直到 6 年前
        1
  •  0
  •   shmit    6 年前

    除了在类中使用public这个词,代码似乎都能找到。除去它们。

    export class allFunctions {
    
        static makeChanges(a, b, c) {
            ...
            this.callUpdate(c, d);
        }
    
        static callUpdate(c, d) {
            otherFunctions.makeUpdate();
        }
    
    }
        2
  •  0
  •   zilijonas    6 年前

    我终于找到了解决办法。我需要使用spy而不是jest.fn();

    解决方案如下:

    import { allFunctions } from '../allFunctions';
    
    describe('simple test', () => {
    
        it('makeChanges() should call callUpdate()', () => {
    
            const a = 1, b = 2, ...;
    
            const spy = jest.spyOn(allFunctions, 'callUpdate');
    
            allFunctions.makeChanges(a,b,c);
    
            expect(spy).toHaveBeenCalled();
    
        });
    
    });