Justin
Justin

Reputation: 2039

Have multiple Mocha unit-tests execute, contingent on the result of other unit test results

I'm writing some unit tests for a NodeJS application I'm working on, and I have a question regarding some unit-testing logic.

Lets say the application creates a "Group" for users, then creates some individual Users, then adds the users to said group, these are all async functions by the way (MongoDB)

I wanted to have one test case that would test if the group was successfully created, then a separate one for testing the user creation, then the user -> account association.

Obviously, if the Group fails, or the Users fail, then it doesn't make sense to execute the User -> Group association unit test. Should I write some logic in the Unit test to check if there was an error (after the expect(err).to.equal(null)), and if its null, THEN execute the other test case(s)? Thats the only logic that makes sense to me, but I didn't see any of that type of logic in any unit tests in any other packages (I looked at some unit tests to see if I could spot something similar to this)

Also, If I have multiple test cases that interact with a newly created User, should each one of those test cases attempt to create a user, then go on with its own unique test? Or should I try to structure it so it all interacts with the user that was just created (if it was successful)

For example:

describe('User', function () {
    describe( '.createUser', function() {
        it( 'Create user Foobar', function( done ) {
            // ...
        })
    } )

    describe( '.updateContacts', function() {
        it( 'Update contacts for user Foobar', function( done ) {
            // ...
        })
    } )

    describe( '.changePassword', function() {
        it( 'Change password for user Foobar', function( done ) {
            // ...
        })
    } )

    describe( '.deleteUser', function() {
        it( 'Delete user Foobar', function( done ) {
            // ...
        })
    } )
})

Should the updateContacts, changePassword and deleteUser all attempt to create their own user to interact with? That seems like it would be a bit redundant..

Hope I explained this correctly.

Upvotes: 2

Views: 158

Answers (1)

Jayro Salgado
Jayro Salgado

Reputation: 36

its a good practice in unit test to only use before and after mocha methods to insert needed documents for testing, you can use beforeEach and afterEach as well. you can use libraries like sinon and httpMocks to help you creating spies for test the behavior of asynchronous services

Upvotes: 2

Related Questions