title: Testing object assignment in TypeScript
body: <p>I am writing an Azure Function and persisting data to a CosmosDB.
  It works like this:</p>
  
  <pre class="lang-js prettyprint-override"><code>const preloadShipmentTrigger: AzureFunction = async function (context: Context, req: HttpRequest): Promise&lt;void&gt; {
      if (req.body) {
          const body: Body = req.body
  
          context.bindings.cosmosDocument = JSON.stringify(body);
          context.res = {
              status: 200,
              body: 'Successfully persisted document'
          };
      }
  }
  </code></pre>
  
  <p>And here's a test for the same functionality:</p>
  
  <pre class="lang-js prettyprint-override"><code>test('returns 200', async () =&gt; {
      let contextMock: Context = mock&lt;Context&gt;()
  
      const body = createBody()
      const request = {
          body: body
      }
  
      let context = instance(contextMock)
      context.bindings = {
          cosmosDocument: undefined
      }
  
      await httpFunction(context, request)
  
      verify(contextMock.log(`log`)).once()
  
      expect(context.bindings.cosmosDocument).toBeDefined()
      expect(context.bindings.cosmosDocument).toEqual(JSON.stringify(body))
  
      expect(context.res).toBeDefined()
      expect(context.res!.status).toBe(200)
      expect(context.res!.body).toBe('Successfully persisted document')
  })
  </code></pre>
  
  <p>Bindings in the <code>Context</code> object looks like this in the definition:</p>
  
  <pre class="lang-js prettyprint-override"><code>/**
   * Input and trigger binding data, as defined in function.json. Properties on this object are dynamically
   * generated and named based off of the "name" property in function.json.
   */
  bindings: {
      [key: string]: any;
  };
  </code></pre>
  
  <p>I am using ts-mockito for this.</p>
  
  <p>Now I'd like to test what happens when the object assignment fails, e.g. writing to database fails:</p>
  
  <pre class="lang-js prettyprint-override"><code>when(context.bindings.cosmosDocument).thenThrow(new Error(''))
  </code></pre>
  
  <p>Obviously this won't work since cosmosDocument is not a mock:</p>
  
  <blockquote>
    <p>TypeError: this.methodToStub is not a function</p>
  </blockquote>
  
  <p>How can do I do this in TypeScript? Is it a simple matter to rearrange my code, or do I have to dive into mechanics of the Azure Function framework?</p>