2015-01-08 14 views
10

tôi nhận được như thế nào để còn sơ khai mô hình Mongoose (nhờ Stubbing a Mongoose model with Sinon), nhưng tôi không hoàn toàn hiểu làm thế nào để còn sơ khai cuộc gọi như:Sử dụng Sinon để Stub xích Mongoose gọi

myModel.findOne({"id": someId}) 
    .where("someBooleanProperty").equals(true) 
    ... 
    .exec(someCallback); 

tôi thử như sau:

var findOneStub = sinon.stub(mongoose.Model, "findOne"); 
sinon.stub(findOneStub, "exec").yields(someFakeParameter); 

không có kết quả, bất cứ đề nghị?

Trả lời

14

Tôi đã giải quyết nó bằng cách làm như sau:

var mockFindOne = { 
    where: function() { 
     return this; 
    }, 
    equals: function() { 
     return this; 
    }, 
    exec: function (callback) { 
     callback(null, "some fake expected return value"); 
    } 
}; 

sinon.stub(mongoose.Model, "findOne").returns(mockFindOne); 
7

Hãy xem để sinon-mongoose. Bạn có thể mong đợi các phương pháp xích chỉ với một vài dòng:

sinon.mock(YourModel).expects('findOne') 
    .chain('where').withArgs('someBooleanProperty') 
    .chain('exec') 
    .yields(someError, someResult); 

Bạn có thể tìm các ví dụ hoạt động trên repo.

Ngoài ra, đề xuất: sử dụng phương pháp mock thay vì stub, điều đó sẽ kiểm tra phương thức thực sự tồn tại.

+1

này mang lại cho tôi: "TypeError: sinon.stub (...) .không phải là một hàm" – schw4ndi

+1

@ schw4ndi bạn đang sử dụng 'sinon.stub' thay vì' sinon.mock'. Cho tôi biết nếu điều đó không giải quyết được vấn đề của bạn. – Gon

1

Nếu bạn sử dụng Promise, bạn có thể thử sinon-as-promised:

sinon.stub(Mongoose.Model, 'findOne').returns({ 
    exec: sinon.stub().rejects(new Error('pants')) 
    //exec: sinon.stub(). resolves(yourExepctedValue) 
}); 
1

Một cách khác là còn sơ khai hoặc do thám các chức năng nguyên mẫu của Query tạo (sử dụng Sinon):

const mongoose = require('mongoose'); 

sinon.spy(mongoose.Query.prototype, 'where'); 
sinon.spy(mongoose.Query.prototype, 'equals'); 
const query_result = []; 
sinon.stub(mongoose.Query.prototype, 'exec').yieldsAsync(null, query_result); 
Các vấn đề liên quan