Search code examples
node.jssupertest

reset a database before each test


I'm using node and supertest for a simple app. I got SQlite3 for the local test database. I did a simple test to get a super inserted into the database. I wanted to reset the database each time a test is run. I'm looking in the docs right now and can't seem to locate it. I figured I would ask here because it seems someone would most likely know the info.

const request = require('supertest');
const server = require('../server');

describe('Authentication', function() {

//database reset here

  it('should create a new user /users/registration', function(done) {
    request(server)
      .post('/users/register')
      .send({
        username: 'user-name',
        email: '[email protected]',
        password: '12345'
      })
      .set('Accept', 'application/json')
      .expect(201, done);
  });
});

Solution

  • If you want to run any piece of code before each test, you can use beforeEach function in jest

    describe('my test', () => {
        beforeEach(() => {
           // code to run before each test
        });
    
        test('test 1', () => {
          // code
        });
    
       test('test 2', () => {
          // code
       });
    });