javascriptunit-testingrsvp.js

Method under test appearing in unit test other than in the action


I was wondering if anyone could give me some pointers on designing my unit tests, specifically where the function being tested appears in the test itself other than in the unit's action.

I'm writing server side javascript with node and using rsvp for asynchronous calls to a restful backend.

I structure my unit tests as follows.

//Setup
//Action
//Assertion
//Cleanup

Right now, I'm building a function which asynchronously deletes enteries in a database so my unit test looks like this.

"deletingFunction_1entry_returns1EntryDeleted": function() {
      return new rsvp.Promise(function( resolve, reject ) {
      //Setup
      var DatabaseEntry = { "Info": "Info" };
      setup( DatabaseEntry ).then(function( xPostedEntries ) {
      //if the setup promise resolves then...
          //Action
          xDelete( xPostedEntries ).then(function( xDeletedEnteries ) {
              //Assertion
              if ( xPostedEntries === xDeletedEntries ) {
              //if the posted enteries matched the deleted enteries then...
                  resolve();
              } else {
              //otherwise the posted enteries did not match the deleted  
              //enteries so...
                  reject("The posted enteries did not match the deleted enteries.");
              }    
          });
      }, function( xPostedEnteries ) {
      //otherwise the setup promise did not resolve so...
          //Cleanup
          /***************************************************************/
          /* Here's where I'm having trouble. If the setup fails to post */
          /* all of the entries to the database then the test is a       */                              
          /* scratch but I want to clean up all the posts that 'were'    */
          /* posted but to remove them from the database, I'd be using a */
          /* deleting function, which is the function that I'm testing.  */
          /* So how can I redesign my unit test not to use the function  */
          /* that it's testing.                                          */
          /***************************************************************/
          reject("The setup failed.");   
      });
});

}

Edited: I wrote a function which truncates the database table for clean up but would still appreciate pointers on how to improve my testing.


Solution

  • This isn't a unit test because it has side-effects. Of course you can't use the "delete" function that you're testing. It doesn't even exist until it passes its unit tests. Your unit test needs to be a unit test.

    Probably, you want the database connection to be dependency injected, as an abstract datastore. The unit test will use a mock datastore.