2016-04-28 89 views
2

我有一些代碼,我試圖用這樣的結構(每Cleaning up sinon stubs easily)測試:測試異步運行時,如何使用sinon沙箱?

function test1() { 
    // manually create and restore the sandbox 
    var sandbox; 
    beforeEach(function() { 
     sandbox = sinon.sandbox.create(); 
     sandbox.stub(globalVar, "method", function() { return 1; }); 
    }); 

    afterEach(function() { 
     sandbox.restore(); 
    }); 

    it('tests something', function(done) { 
     anAsyncMethod(function() { doSomething(); done(); }); 
    } 
} 

然後有一個類似的測試2()函數。

但是,如果我做的:

describe('two tests', function() { 
    test1(); 
    test2(); 
} 

我得到:

TypeError: Attempted to wrap method which is already wrapped 

我已經做了一些記錄,以找出運行秩序,它看來,問題是,它運行test1 beforeEach() hook,然後test2 beforeEach()掛鉤,然後test1 it()等。因爲它在從第一次測試到達afterEach()之前調用第二個beforeEach(),所以我們遇到了問題。

有沒有更好的方法我應該構造這個?

回答

1

測試規範的結構應該是這個樣子:

describe("A spec (with setup and tear-down)", function() { 
    var sandbox; 

    beforeEach(function() { 
    sandbox = sinon.sandbox.create(); 
    sandbox.stub(globalVar, "method", function() { return 1; }); 
    }); 

    afterEach(function() { 
    sandbox.restore(); 
    }); 

    it("should test1", function() { 
    ... 
    }); 

    it("should test2", function() { 
    ... 
    }); 
}); 

或者你可以這樣做:

function test1() { 
    ... 
} 

function test2() { 
    ... 
} 

describe("A spec (with setup and tear-down)", function() { 
    describe("test1", test1); 
    describe("test2", test2); 
}); 
+0

但我希望能夠把這兩個規格的功能所以我可以重複使用它們進行各種測試。我想讓它們自成一體,所以我不必在每次打電話時都創建沙箱和存根代碼。這不可能嗎? –

+0

我明白你的意思了。讓我更新我的答案 - 在評論中格式化代碼仍然是新的。 –

+0

額外描述的包裝 - 無論你是擁有它還是隻是在每個測試函數中 - 都可以。額外的報告層次,但似乎是可能的。謝謝。 –