简体   繁体   中英

Using Mocha Chai with Stormpath

My google-fu may have failed me, but I'm looking into building unit tests for an Express app that uses Stormpath for authentication. So a typical route looks something like this;

app.get('/api/user', stormpath.loginRequired, userApi.get);

How would I make use of a testing framework like Mocha + Chai in this case?

Thanks @rdegges, that led me to find a good solution. I can see how to create a test user account in stormpath, but in my case I'm happy to have a test user already setup in Stormpath. So I just need to create the session, and then have the actual test run (so I just need Chai to keep the session). So here is a solution I ended up with.

        var agent = chai.request.agent(server);

        agent
           .post('/login')
           .set('Accept', 'application/json')
           .set('Content-Type', 'application/x-www-form-urlencoded')
           .send({ login: '<username>', password: '<password>' })
           .then(function (res) {

               // The `agent` now has the session cookie saved, and will send it
               // back to the server in the next request:
               agent
                    .put('/user')
                    .send({user:data})
                    .end((err, res) => {

                        if (err){
                            Logger.error(res.text);
                        }

                        res.should.have.status(200);

                        // Do testing here
                        done();
                    });
            });

看看我在 express-stormpath 库中编写的集成测试,例如: https : //github.com/stormpath/express-stormpath/blob/master/test/middlewares/test-groups-required。 js#L208

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM