2017-12-01 30 views
0

우리는 일부 테스트에서 익스프레스 앱에 인증 미들웨어를 작성하려고하고 있으며 스터 빙 작업을 수행하는 데 어려움을 겪고 있습니다.Sinon으로 auth 기능을 스텁 및 복원하면 스텁을 사용하는 모카 테스트가 발생합니다.

우리의 모카 시험은 다음과 같이 보입니다 : 가 ('primaryDeal 경로 단위 테스트'를 설명,() =>를 {첫 it를 대상으로하지만, 스텁하지에 나타나는

describe('Authentication allows for data fetching',() => { 
     let app; 
     let getPrimaryDealData; 
     let queryParams; 
     let isAuthenticated;  
     let count = 0; 

     beforeEach(() => { 
      // console.log(isAuthenticated); 
      if (count === 0) { 
       isAuthenticated = sinon.stub(authCheck, 'isAuthenticated'); 
       isAuthenticated.callsArg(2); 
      } 
      app = require('../../lib/index.js'); 
     }); 


     afterEach(() => { 
      if (count === 0) { 
       isAuthenticated.restore(); 
      } 
      app.close(); 
      count++; 
     }); 

     it(('should send an API request, validate input and return 200 response'),() => { 
      return chai.request(app) 
       .get('/api/contracts/') 
       .then((res) => { 
        expect(res).to.have.status(200); 
       }); 
     }); 

     it(('should respond with forbidden'),() => {  

      app = require('../../lib/index.js');  

      return chai.request(app) 
       .get('/api/contracts/') 
       .catch((res, err) => { 
        expect(res).to.have.status(403); 
       }); 
     }); 
    });  
}); 

우리의 스텁 작품 it에 대해 복원해야하고 인증 미들웨어가 실행되고 있지 않습니다. 다른 테스트에서 주석이없는 경우 두 테스트가 모두 작동합니다.

이 블록을 다른 파일로 분리하려고 시도했으며 다른 describe 블록의 순서를 바꿔 보았습니다.개의 블록이 있으며, 우리는 chai.request(app) 개의 서버를 동시에 제공하려고 노력했지만 손실이 있습니다.

두 번째 it 문이 Auth 미들웨어를 호출하지 않는 이유는 무엇입니까?

답변

0

샌드 박스를 사용하는 것이 좋습니다. 사용하는 것이 더 우아합니다. 스텁을 개별적으로 복원 할 필요가 없습니다. 여기에 샘플입니다 : 또한

let sandbox; 
 

 
beforeEach(() => { 
 
    sandbox = sinon.sandbox.create(); 
 

 
    isAuthenticated = sandbox.stub(authCheck, 'isAuthenticated'); 
 
}); 
 

 

 
afterEach(() => { 
 
    sandbox.restore(); 
 
});

는 수 바꿀 추가하려고,

app = require('../../lib/index.js');

delete require.cache[require.resolve('../../lib/index.js')] 
 
app = require('../../lib/index.js');
,

또 다른 생각인데, reset이 아닌 restore을 사용해야 할 수도 있습니다.

P. index.js 소스도 확인하는 것이 좋습니다