【发布时间】:2020-01-24 16:01:40
【问题描述】:
我发现我在一个 Node.js REST API 的多个集成测试中有很多重复的测试用例。例如,我测试每个端点的无效请求,我希望错误总是具有相同的属性。
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 是否提供任何方法来创建一些共享测试,以便我可以封装此错误验证并在其他套件案例中声明它以避免如此多的重复?
【问题讨论】:
标签: javascript node.js express jestjs supertest