我在所有测试中使用相同的 before() 和 after() 根级别挂钩来设置和清除我的测试数据库......有没有办法将它们移动到文件中并导出/导入该文件?
是的。我能够通过利用 mocha 的this
上下文来实现这种行为,在他们关于共享行为的 Wiki 文章中进行了讨论。我正在使用ts-mocha
异步/等待功能的帐户。
所以我编写了使用登录和注销的函数supertest-session
,它看起来像这样:
export function authHooks()
{
const email = UsersSeed[0].email;
const password = UsersSeed[0].password;
before(`login ${email}`, async function()
{
await this.session.post('/api/account/login')
.send({ email, password })
.expect(201);
});
after(`logout ${email}`, async function()
{
await this.session.get('/api/account/logout')
.expect(200);
});
}
在我的内部describe
我设置了this.session
并且在我的it
-statements 中我可以重用它。它看起来有点像这样:
import { expect } from 'chai';
import * as Session from 'supertest-session';
import { authHooks } from './authHooks';
describe('Some Suite', () =>
{
before(function()
{
this.session = new Session(SomeApp);
});
after(function()
{
this.session.destroy();
});
describe('when not authenticated', () =>
{
it('returns 403', async function()
{
await this.session.get('/api/jobs')
.expect(403)
.expect({ statusCode: 403, message: 'Forbidden resource' });
});
});
describe('when authenticated', () =>
{
authHooks();
describe('when finding jobs', () =>
{
it('returns all jobs', async function()
{
await this.session.get('/api/jobs')
.expect(200)
.then((response) =>
{
expect(response.body).to.deep.eq(SomeThing);
});
});
});
});
});
我不确定这是否是实现它的最佳方式(我不喜欢个人function
过度使用() => {}
),但我已经确认它有效。
上面的代码不会运行,主要是因为我在保护代码细节,但希望这将为您提供至少一个选项,也许其他人可以展示更好的方法来做到这一点。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句