【问题标题】:Unit Test function that returns Mongoose promise返回 Mongoose 承诺的单元测试函数
【发布时间】:2016-10-04 13:44:08
【问题描述】:

要测试的代码

import { User } from '../models/no-sql/user';

function userCreate(req) {
    const user = new User({
       username: req.username,
        password: req.password
    });

   return user.save();
}

app.get('/userCreate', function(req, res) {
    User.findOne({ username: req.username }).lean().exec((err, data) => {
        if(data){
            userCreate(req).then(function() {
                // success
            }, function(err) {
                // error
            });
        }else{
        // no user found
        }   
    });
});

单元测试

    require('sinon-as-promised');
    import request from 'supertest';

    const user = {
        username: newUserName,
        password: 'password'
    };


    factory.build('user', user,  function(err, userDocument) {
        UserMock.
            expects('findOne').withArgs(sinon.match.any)
            .chain('lean')
            .chain('exec')
            .yields( null, undefined);

        const docMock = sinon.mock(userDocument);
        docMock.expects('save')
        .resolves([]);

        request(app)
        .post('/userCreate')
        .send({username: newUserName, password: 'password')
        .expect(200)
        .end((err, res) => {
            if(err) done(err);
            should.not.exist(err);
            should.equal(res.body.success, true);
            done();
        });
});

测试到达返回 user.save() 然后超时。似乎我在单元测试中遗漏了一些东西,但是没有抛出错误。我正在使用 sinon-as-promised 来解决承诺,但它似乎没有看到它。

【问题讨论】:

    标签: mongodb unit-testing mongoose factory-bot sinon


    【解决方案1】:

    为了简洁起见,您似乎不太可能故意在示例代码中省略 res.send() 调用。

    只是为了确保,当路由器中调用的 userCreate 函数成功时,您是否返回 200 状态码?

    userCreate(req).then(function() {
       // success
       res.status(200).send('User created successfully');
    }
    

    【讨论】:

    • 当 userCreate 被休息客户端击中时,它工作正常我排除了响应为清楚起见,但在 userCreate.then 函数之后测试没有达到返回 `
    猜你喜欢
    • 2018-01-21
    • 2017-04-07
    • 2018-07-27
    • 2021-07-23
    • 2014-05-19
    • 2017-05-26
    • 2021-09-07
    • 2019-04-05
    • 2017-05-08
    相关资源
    最近更新 更多