2017-12-15 25 views
0

나는 내가 좋아하는 일을하고 하나의 돛 컨트롤러가 있습니다. myFunc의 단위 테스트를 작성할 수 있지만 asynFunc (데이터 가져 오기, 데이터 유효성 검사)를 작성할 수는 없습니다.단위 테스트는 독립적으로

알려 주시기 바랍니다 :

  1. 어떻게 조롱 수 asyncFunc
  2. 내가 어떻게 단위 테스트 asynFunc

답변

0

당신이 정말로 개인 기능을 테스트해야합니까? 비공개로 설정 한 경우 다른 방법을 테스트 할 때 테스트 할 수 있습니다. myModule.js

async function asyncFunc(){ 
 
    /* some logic */ 
 
} 
 
module.exports = { 
 
    myFunc: async function() { 
 
    // Call async function and return 
 
    await asyncFunc(); 
 
    return true; 
 
    } 
 
};

test.js

const rewire = require('rewire'); 
 
const myModule = rewire('./myModule'); 
 

 
describe('unit/myModule:',() => { 
 
    const revert = (obj) => { 
 
    obj.__revert__(); 
 
    delete obj.__revert__; 
 
    }; 
 

 
    it('asyncFunc', async() => { 
 
    const asyncFuncSpy = jasmine.createSpy(); 
 
    asyncFuncSpy.__revert__ = myModule.__set__('asyncFunc', asyncFuncSpy); 
 

 
    const actual = await myModule.myFunc(); 
 

 
    expect(actual).toBeThruthy(); 
 
    expect(asyncFuncSpy).toHaveBeenCalled(); 
 

 
    revert(asyncFuncSpy) 
 
    }) 
 
})

0
: 당신이 정말로 그것을 테스트해야하는 경우

는 다음을 수행 할 수 있습니다

99 %의 경우 컨트롤러 사용이 좋지 않습니다! 해당 기능을 서비스로 통합하고 단일성으로 서비스를 테스트하십시오.

// Controller 
module.exports = { 
    myFunc: function() { 

    // Call async function and return 
    MyService.asynFunc(); 
    return true; 
    } 
}; 

// Service 
module.exports = { 
    async : function asynFunc(){ 
    /* some logic */ 

    } 
}