2016-12-14 1 views
1

테스트 결과는 다음과 같이 구성되어 있습니다 스텁됩니다 실행하면,이 테스트는 모든 TypeError: harness.spy is not a function에 실패모카 테스트, 모의을 감시하기 위해 접근을 잃고, 그리고

describe("description", sinon.test(function() { 
    const harness = this; 
    it("should do something", function() { 
     // do something with harness.spy, harness.mock, harness.stub 
    }); 
})); 

. 몇 가지 로그를 추가했고 harness.spy이 있고 함수가 it에 전달되기 전에 함수임을 알았지 만 it에 전달 된 함수 내에서 harness.spyundefined입니다.

여기에서 무슨 일이 일어나고 있는지 이해하는 데 도움이 될 것입니다.

답변

1

문제는 모카가 코드를 실행하는 순서입니다. 콜백을 describe으로 마무리하면 sinon.test으로 작동하지 않습니다. 그 이유는 모두 describe에 대한 콜백이 의 실행을 완료하기 전에의 테스트 중 하나라도 it의 실행을 시작하기 때문입니다. sinon.test 작동하는 방식, 그것은 샌드 박스 (spy, stub 등)의 몇 가지 방법으로 새로운 샌드 박스, 악기 this를 생성 한 후 콜백을 호출하고, sinon.testthis에서 콜백 수익률을 제거 할 때 방법이 그것을 덧붙여서.

따라서 describe 콜백을 래핑하는 sinon.test에 의해 수행 된 설정은 테스트가 실행되기 전에 실행 취소됩니다. 다음은 몇 가지를 넣은 예제입니다. console.log. 테스트가 실행되기 전에 console.log 문이 모두 실행됩니다.

const sinon = require("sinon"); 

describe("description", sinon.test(function() { 
    const harness = this; 
    it("should do something", function() { 
    }); 

    console.log("end of describe"); 
})); 

console.log("outside"); 

이 같이 대신, 당신은 it에 전달하는 콜백을 포장해야합니다 sinon.test에 의해 생성 된 샌드 박스의 수명이 당신을 위해 작동하지 않습니다

const sinon = require("sinon"); 

describe("description", function() { 
    it("should do something", sinon.test(function() { 
     this.spy(); 
    })); 
}); 

console.log("outside"); 

경우에, 당신은 만들어야합니다 샌드 박스를 제거하고 "수동"으로 청소하려면 다음과 같이하십시오.

const sinon = require("sinon"); 

describe("description", function() { 
    let sandbox; 
    before(function() { 
     sandbox = sinon.sandbox.create(); 
    }); 
    after(function() { 
     sandbox.restore(); 
    }); 
    it("should do something", function() { 
     sandbox.spy(); 
    }); 
    it("should do something else", function() { 
     // This uses the same sandbox as the previous test. 
     sandbox.spy(); 
    }); 
});