在Jest Supertest中开始集成测试之前清除测试数据库

时间:2018-12-06 11:42:54

标签: node.js express mongoose jestjs supertest

我的user.test.js中有以下代码:

const request = require('supertest');
let server ;
const {User} = require('./../../models/user');





describe('/users', () => {

    beforeEach(() => server =  require('./../../index'));
    afterEach(() => server.close());

    describe('POST /users', () => {

        it('should signup successfully', async () => {




           const res = await 
           request(server).
           post('/users').
           send({ email : 'abc@gmail.com' , password: 'abcassasa'})
           expect(res.status).toBe(200);
        });
    });


})

我想在进行“应该成功注册”测试之前清除数据库,以免创建重复记录,因为电子邮件被设置为唯一验证,因此失败了。

1 个答案:

答案 0 :(得分:0)

我明白了,我只需要这样做:

describe('POST /users', () => {

        beforeEach(async () => {
              await User.remove({});
          });

        it('should signup successfully', async () => {




           const res = await 
           request(server).
           post('/users').
           send({ email : 'sriramhegde@gmail.com' , password: 'Na321tional'})
           expect(res.status).toBe(200);
        });
    });