Node.js+Express+Expressoでセッション情報を持ったまま遷移するテスト
要はログインした状態でどこかのページに行ってテストしたいわけです。
assert.response(server,
{
url: '/login',
method: 'post',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
},
data: 'user[mailaddress]=momota@kana.com&user[password]=chabatake'
},
{status: 200},
function(res) {
assert.response(server,
{
url: '/dosomething-withlogin',
method: 'post',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
},
data: 'text=ganbacchaimaxx!'
},
{status: 200}
);
}
);だいたいこんな感じです。assert.responseの入れ子とかみっともない感じですけど、なんかもっとスマートな書き方あれば教えて下さい。
それで上のコードだと1回目のassert.responseコールバックのresに含まれているクッキーの情報(セッションキー)が2回目のassert.responseに渡されないのでログイン状態が維持されない。じゃあどのようにクッキーを持たせるのか、Expressで使われているConnectのcookieParserソースコードを読むと、単にheadersにcookieを追加すればよいようです。なので以下のコードとなります。
https://github.com/senchalabs/connect/blob/master/lib/middleware/cookieParser.js
assert.response(server,
{
url: '/login',
method: 'post',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
},
data: 'user[mailaddress]=momota@kana.com&user[password]=chabatake'
},
{status: 200},
function(res) {
assert.response(server,
{
url: '/dosomething-withlogin',
method: 'post',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
// 下の1行追加、resはset-cookieなのにreqはcookie
'cookie': res.headers['set-cookie']
},
data: 'text=ganbacchaimaxx!'
},
{status: 200}
);
}
);これでOK