2017-08-16 68 views
0

我试图测试一个函数,调用连接到亚马逊AWS的两个其他函数。考虑到这一点,我不想调用称为AWS的真正函数 - 我试图将它们存根。但是,每次运行我的测试时,它都会调用真正的函数而不是我的存根。未调用存根函数,而是调用实际版本。为什么?

我有点新来测试,可能会失去一些东西,但无法找到任何其他问题的解决方案。 我使用jasminesinon

我的代码如下:因为我不

export function functionA(id: string): Promise<string> {//Return Promise<string> 
//some code 
return anotherFunction(id); 
} 

export function functionB(organizationId: string): Promise<string[]> { 
//Goes to amazon do something and return Promise<string[]> 
} 

我省略functionAfunctionB实施:

const cache = new Map<string, Set<string>>(); 
//Function to be tested - inside class XYZ 
export function functionToBeTest(events: Event[]): Promise<Event[]> { 
    cache.clear(); 
    let promises: Array<Promise<void>> = []; 
    promises = events.map((event) => { 
     let foundId: string; 
     return functionA(event.Id) 
      .then((id: string) => { 
       foundId = id; 
       if (!cache.has(id)) { 
        return functionB(id); 
       } 
      }) 
      .then((regDev) => { 
       cache.set(foundId, new Set(regDev)); 
      }) 
      .catch((err) => { 
       log.error({ err: err }); 
       return Promise.reject(err); 
      }); 
    }); 

    return Promise.all(promises) 
     .then(() => { 
      return Promise.resolve(events) 
     }); 
} 

我想存根功能我不在乎他们做什么或者我只需要将它们存根,因此我测试了functionToBeTest内部的逻辑。

我的测试套件如下:

import * as sinon from 'sinon'; 

describe('testing functionToBeTest()',() => { 

    let stubA: sinon.SinonStub; 
    let stubB: sinon.SinonStub; 

    beforeEach(() => { 
     stubA = sinon.stub(xyz, 'functionA'); 
     stubA.onFirstCall().resolves('1'); 
     stubA.onSecondCall().resolves('2'); 
     stubB = sinon.stub(xyz, 'functionB'); 
     stubB.onFirstCall().resolves(['1']); 
     stubB.onSecondCall().resolves(['2']); 
    }); 

    afterEach(() => { 
     stubA.restore(); 
     stubB.restore(); 
    }); 

    it('should populate the cache', (done) => { 
     let events: Event[] = [ 
      { 
       timestamp: 1, 
       eventType: EventType.PC, 
       id: '1' 
      }, 
      { 
       timestamp: 2, 
       eventType: EventType.BU, 
       id: '2' 
      } 
     ]; 
     xyz.functionToBeTest(events)// Here should call the real function and inside it should call the stub functions 
     .then((result) => { 
      //expectations 
     }) 
     .then(() => { 
      done(); 
     }) 
     .catch((err) => { 
      done.fail(err); 
     }); 
    }); 
}); 

正如我所说的,当我运行这个测试它永远不会调用存根函数,总是从实际函数中返回我的错误(应该存根)。

任何人都可以帮忙吗?我可能做错了存根,但我看不出有什么问题。

回答

0

找出它是一个有问题的参考。不是调用方法存根,而是调用真正的存根。为了解决这个问题,我不得不改变我原来的课程出口,并使用public static关于我想在外面使用的方法。