DEV Community

Discussion on: Reseed your database with Cypress

Collapse
 
lcpautotester profile image
lcpautotester

Where is your GIT examples?

It would nice to see your JS code.

i've stayed with EF , just because there is no eazy way to setup and tear down SQL data in Cypress that I was aware of

Collapse
 
timdeschryver profile image
Tim Deschryver • Edited

The teardown is a sql script that runs (via the mssql package) :
It basically looks for all tables to delete, removes the constraints, deletes all the data, re-enables the constraints, and reseeds the identity column

module.exports = () => {
  console.log('[DATABASE TEARDOWN] Started');
  return require('./utils/run-script.js').run`
    DECLARE @statement nvarchar(MAX);
    DECLARE @statements CURSOR;
    SET @statements = CURSOR FOR
      with tables as (
        SELECT SCHEMA_NAME(schema_id) 'SchemaName', name 'TableName', '['+SCHEMA_NAME(schema_id)+'].['+name+']' 'SchemaTableName'
        FROM sys.tables
      ),
      mocktables as (
        select *
        from tables
        where SchemaName not in ('dbo', 'Foo')
      ),
      statememts as (
        select 'ALTER TABLE ' + SchemaTableName + ' NOCHECK CONSTRAINT ALL;' as statememt
        from mocktables
        union all
        select 'DELETE FROM ' + SchemaTableName + ' ;'
        from mocktables
        union all
        select 'ALTER TABLE ' + SchemaTableName + ' CHECK CONSTRAINT ALL;'
        from mocktables
        union all
        select 'DBCC CHECKIDENT ( ''' + SchemaTableName + ''', RESEED, 0) WITH NO_INFOMSGS;'
        from mocktables
      )
    SELECT *
    FROM statememts
    OPTION (MAXRECURSION 0)
    OPEN @statements
    FETCH next FROM @statements INTO @statement
    WHILE @@fetch_status = 0
    BEGIN
        exec sp_executesql  @statement
        FETCH next FROM @statements INTO @statement
    END;
`.then(() => {
    console.log('[DATABASE TEARDOWN] Ended');
    return true;
  });
};
Collapse
 
ridergriffin_ profile image
rider

Hello, I've been working on some e2e testing based in typescript and using cypress. I really like how you've taken the approach to this, as SQL data is hard to manage in cypress. Is there any way I could see how you performed your seed task? Did you use hardcoded json or yaml data as a fixture and pass that in to the server?

Thread Thread
 
timdeschryver profile image
Tim Deschryver

The data is created with JS, but is just a JSON.
We did it with JS, so we could use some helper functions.
In short, we create a collection of JS objects which structure is the same as our SQL tables.
Afterward, we generate insert statements from these objects.