簡體   English   中英

如何將數據傳遞給mongoose模式構造函數

[英]How to get data passed to mongoose schema constructor

我正在測試我的應用程序,需要驗證是否使用正確的數據調用了mongoose模式構造函數。

讓我說我這樣做:

const UserData = new User(user)
console.log(UserData.contructor.args)

我希望user對象的日志。 可能數據傳遞給mongoose模式的構造函數?

有人可以告訴我如何訪問它?

這是我試圖解決的具體案例。

export const signup = async (req, res, next) => {
    try {

        //if user object is missing return error
        if (!req.body.user) 
            return next(boom.unauthorized('No user data received.'))        

        //get user data    
        const user                                      = req.body.user,
        { auth: { local: { password, password_2 } } }   = user        

        //check if both passwords match
        if (password !== password_2)
            return next(boom.unauthorized('Passwords do not match.'))

        //check if password is valid
        if (!Password.validate(password)) {          
            const errorData = Password.validate(password, { list: true })
            return next(boom.notAcceptable('Invalid password.', errorData))
        }    

        //creates new mongo user
        const UserData = new User(user)

        //sets user password hash   
        UserData.setPassword(password)

        //saves user to database
        await UserData.save()        

        //returns new users authorization data
        return res.json({ user: UserData.toAuthJSON() })

    } catch(err) {

        //if mongo validation error return callback with error       
        if(err.name === 'ValidationError') {
            return next(boom.unauthorized(err.message))
        }

        // all other server errors           
        return next(boom.badImplementation('Something went wrong', err))
    }

}

部分測試:

describe('Success', () => {
            it('Should create new instance of User with request data', async () => {
                const   req             = { body },
                        res             = {},
                        local           = { password: '1aaaBB', password_2: '1aaaBB'},
                        constructorStub = sandbox.stub(User.prototype, 'constructor')                

                req.body.user.auth.local    = {...local}

                await signup(req, res, next)

                expect(constructorStub.calledOnceWith({...req.body.user})).to.be.true

            })                
        })

編輯:我可以驗證是否使用expect(constructorStub.calledOnce).to.be.true

只是無法驗證傳遞的數據。

編輯:在談了一段時間后聽起來像你需要的是驗證你正在創建一個新用戶。

我的建議是創建一個新函數createUserFromRequest ,它將接收request並返回一個new User

然后,您可以輕松地測試此功能,因為它是純粹的(沒有副作用,只是輸入和輸出)。

此時,處理程序中的大多數邏輯都在此函數中,因此可能不值得測試處理程序本身,但您仍然可以執行此操作,例如通過模擬上面的函數。

例:

function createUserFromRequest(request) {
    //get user data    
    const user                                      = req.body.user,
    { auth: { local: { password, password_2 } } }   = user        

    //check if both passwords match
    if (password !== password_2)
        return next(boom.unauthorized('Passwords do not match.'))

    //check if password is valid
    if (!Password.validate(password)) {          
        const errorData = Password.validate(password, { list: true })
        return next(boom.notAcceptable('Invalid password.', errorData))
    }    

    //creates new mongo user
    const UserData = new User(user)

    //sets user password hash   
    UserData.setPassword(password)
    return UserData;
}

請注意 :存根和模擬通常是代碼味道:可能有更好的測試方法,或者它可能是需要將代碼重構為更容易測試的東西的跡象。 它們通常指向緊密耦合或混亂的代碼。

看看這篇關於該主題的精彩文章: https//medium.com/javascript-scene/mocking-is-a-code-smell-944a70c90a6a

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM