title: Unit testing mongo map reduce functions with both local scope and object scope variables
body: <p>I would like to unit test JavaScript functions used for querying MongoDB with map reduce algorithm.</p>
  <h3>Simple map function</h3>
  <pre><code>function mapFunction() {
     if(key !== this.key) {
        return;
     }
     // do reduce logic
  }
  </code></pre>
  <ul>
  <li><code>this.key</code> variable is MongoDB's object property (<code>this</code> provides access to all properties of such object).</li>
  <li><code>key</code> is a scope variable (scope object is provided to the map reduce query separately).</li>
  </ul>
  <p>The purpose of <code>mapFunction</code>'s <code>if</code> statement is, simply, to ignore MongoDB objects when their key does not match one provided in the scope.</p>
  <h3>Unit testing map function</h3>
  <p>To simulate MongoDB context, both <code>key</code> and <code>this.key</code> variables need to be set by the test framework.</p>
  <p>Mocking <code>this.key</code> can be easily done by using <code>Function.prototype.apply</code> function:</p>
  <pre><code>var mongoContext = {
     key: &quot;sampleKey&quot;
  };
  mapFunction.apply(mongoContext);
  </code></pre>
  <h3>Question</h3>
  <p>I would like to know how to mock <code>key</code> value in this case.</p>