Javascript 如何使用Jest在多个套件中共享测试用例?
我发现在Node.js REST API中的多个集成测试中有许多重复测试案例。例如,我测试每个端点的无效请求,我希望错误总是具有相同的属性Javascript 如何使用Jest在多个套件中共享测试用例?,javascript,node.js,express,jestjs,supertest,Javascript,Node.js,Express,Jestjs,Supertest,我发现在Node.js REST API中的多个集成测试中有许多重复测试案例。例如,我测试每个端点的无效请求,我希望错误总是具有相同的属性 import { app } from 'server'; import * as request from 'supertest'; describe('Authentication tests', () => { describe('POST /login', () => { // other test cases
import { app } from 'server';
import * as request from 'supertest';
describe('Authentication tests', () => {
describe('POST /login', () => {
// other test cases
// describe('valid request should ...', () => {...})
describe('invalid requests with missing fields', () => {
let response = null;
beforeAll(async () => {
await request(app)
.post('/login')
.expect('Content-Type', 'application/json; charset=utf-8')
.field('email', 'invalid@test.com')
.then(res => {
response = res;
});
});
it('should return an invalid status code', () => {
expect(response.status).toBe(400);
});
it('should return a valid error schema', () => {
expect(typeof response.body).toBe('object');
expect(response.body).toHaveProperty('error');
expect(response.body.error).toHaveProperty('code');
expect(response.body.error).toHaveProperty('message');
});
it('should return an error with explicit message', () => {
expect(response.body.error).toHaveProperty('message');
});
});
});
});
Jest是否提供了创建一些共享测试的方法,以便我可以封装此错误验证并在其他套件案例中声明它,从而避免如此多的重复 您可以将这些测试封装到函数中。报告说: 必须同步定义测试,Jest才能收集测试 例如:
函数createInvalidRequestTests(){
描述('无效请求',()=>{
让我们回应;
之前(异步()=>{
//模拟supertest的请求
response=wait Promise.resolve({状态:400,正文:{错误:{代码:1,消息:'networkerror'}});
});
它('应返回无效的状态代码',()=>{
expect(response.status),toBe(400);
});
它('应返回有效的错误模式',()=>{
expect(type of response.body).toBe('object');
expect(response.body).toHaveProperty('error');
expect(response.body.error).toHaveProperty('code');
expect(response.body.error).toHaveProperty('message');
});
它('应返回带有显式消息的错误',()=>{
expect(response.body.error).toHaveProperty('message');
});
});
}
然后,可以使用此函数定义测试。Jest测试运行程序将像往常一样收集并运行这些测试
描述('身份验证测试',()=>{
描述('发布/登录',()=>{
描述('有效请求',()=>{
它('应该正确登录',()=>{
期望(1),期望(1);
});
});
createInvalidRequestTests();
});
描述('POST/register',()=>{
描述('有效请求',()=>{
它('应该正确注册',()=>{
期望(2),期望(2);
});
});
createInvalidRequestTests();
});
});
单元测试结果:
PASS src/stackoverflow/58081822/index.spec.ts(9.622s)
认证测试
发布/登录
有效请求
✓ 应正确登录(5毫秒)
无效请求
✓ 应返回无效的状态代码
✓ 应返回有效的错误模式(2ms)
✓ 应返回带有显式消息的错误
邮寄/登记
有效请求
✓ 应正确注册(1ms)
无效请求
✓ 应返回无效的状态代码(1ms)
✓ 应返回有效的错误模式(2ms)
✓ 应返回带有显式消息的错误(1ms)
测试套件:1个通过,共1个
测试:8项通过,共8项
快照:共0个
时间:12.053秒,估计14秒