【问题标题】:Jest spyOn methodJest spyOn 方法
【发布时间】:2019-02-18 15:17:15
【问题描述】:

我有一个这样的玩笑测试

    import * as source from '../source
      ("Spy on a method", ()=>{
        const spy = jest.spyOn(source, 'toBeCalledOn')
        const result = source.entrypoint(0);
        expect(source.toBeCalledOn()).toHaveBeenCalled();
        })

在我的 srcjs 中

export const entrypoint = (input)=>{
    toBeCalledOn(input)
}


const toBeCalledOn =(input)=>{
    console.log();
}

我希望“toBeCalledOn”能够通过我的开玩笑测试,但我总是失败 -

Expected toBeCalledOn toHaveBeenCalled but wasn't

如何使用jestspy 查看某个方法是否在特定条件下被调用,例如if 语句?

如果我错了,请纠正我,但调用该方法只是为了检查它是否已被调用,这对我来说似乎相当明显。

【问题讨论】:

    标签: javascript unit-testing jestjs


    【解决方案1】:

    您必须期待spyied 函数上的断言而不是实际函数。

    当您在函数上spy 时,永远不会调用实际函数。

    import * as source from '../source'; #import source object or all functions inside of it
    
    describe('Spy on a method', () => {
      it('toBeCalledOn to have been called', () => {
        const spy = jest.spyOn(source, 'toBeCalledOn')
        const result = source.entrypoint(0);
        expect(spy).toHaveBeenCalledTimes(1);
        expect(spy).toHaveBeenCalledWith(0);
      })
    });

    如果你想测试一个条件,你还必须覆盖由于该功能而发生的分支。

    如果您有 ifelse 语句,那么您将需要编写 2 个测试。请看下面的例子。

    export const entrypoint = (input)=>{
      if(input !== 0){
        toBeCalledOn(input);
      }
    }
    
    const toBeCalledOn =(input)=>{
        console.log('logs something');
    }
    
    import * as source from '../source
    
    describe('Spy on a method', () => {
      it('toBeCalledOn not to be called', () => {
        const spy = jest.spyOn(source, 'toBeCalledOn')
        const result = source.entrypoint(0);
        expect(spy).not.toHaveBeenCalled();
      });
      
      it('toBeCalledOn to have been called', () => {
        const spy = jest.spyOn(source, 'toBeCalledOn')
        const result = source.entrypoint(1);
        expect(spy).toHaveBeenCalledTimes(1);
        expect(spy).toHaveBeenCalledWith(1);
      });
    });

    回答您的其他问题, 我会说,我们必须assert 一些显而易见的事情。 如果有人对代码进行了任何更改,并且如果它破坏了之前的流程,在这种情况下,您可以在测试用例中捕获错误。

    这就是我们编写测试用例的原因。

    另外,尝试添加严格的断言,以便进行健壮的测试。例如。您可以使用toHaveBeenCalledTimes 函数代替toHaveBeenCalled 来使断言更严格。

    【讨论】:

      猜你喜欢
      • 2022-11-10
      • 1970-01-01
      • 2021-03-14
      • 1970-01-01
      • 2021-08-26
      • 2017-11-29
      • 1970-01-01
      • 2022-12-31
      • 2021-08-21
      相关资源
      最近更新 更多