我有一套测试,如果单独运行,都会通过。但是,如果cookie并行运行,则会检查cookie的值,从而导致测试失败。
问题是每次测试之间都没有清除supertest的cookie。
有没有办法在使用supertest的每个测试之间清除cookie?这与没有提供解决方案的this open issue有关。
我试过了两个:
afterEach(() => {
request(app)
.set('Cookie', [])
})
和:
afterEach(() => {
request(app)
.set('Cookie', '')
})
......无济于事
以下是单独运行的两个测试,但如果并行运行则会失败:
test('It should respond 302 to the wrong url', (done) => {
const accessiblePages = {get_member_accessible_pages: []}
nock('http://localhost:8000')
.log(console.log)
.get('/auth/me/')
.reply(200, accessiblePages)
// Must use j: to work with cookie parser
const cookie = 'userInfo=j:' + encodeURIComponent(
JSON.stringify(accessiblePages))
request(app)
.get('/first-url')
.set('Cookie', cookie)
.expect(302)
.expect('Location', '/new-url')
.then((response) => {
expect(response.statusCode).toBe(302)
done()
})
})
和
test('It should set an updated cookie for the logged in user', (done) => {
const accessiblePages = {get_member_accessible_pages: [123, 456]}
nock('http://localhost:8000')
.log(console.log)
.get('/auth/me/')
.reply(200, accessiblePages)
// Must use j: to work with cookie parser
const userInfoCookie = 'userInfo=j:' + encodeURIComponent(
JSON.stringify(accessiblePages))
const accessTokenCookie = 'accessToken=accessToken'
const requestCookie = [userInfoCookie, accessTokenCookie].join(';')
const responseCookieValue = accessiblePages
request(app)
.get('/first-url')
.set('Cookie', requestCookie)
.expect(200)
.then((response) => {
expect(response.statusCode).toBe(200)
const cookies = setCookie.parse(response)
expect(cookieParser.JSONCookie(cookies[0].value))
.toEqual(responseCookieValue) // FAILS HERE - shows accessiblePages variable from the previous test.
done()
})
})
您可以尝试显式清除在测试中设置的cookie。它可以通过NPM模块'js-cookies'或通过简单的辅助函数完成:
function removeCookie(name) {
document.cookie = `${name}=1; expires=1 Jan 1970 00:00:00 GMT;`
}
如果您想立即清理所有cookie,可以使用this解决方案。