0

I recently started writing unit tests, and started to move onto integration tests. I have this rather simple method, but I am a bit lost on how to approach or even how exactly to test this.

list (token, cb) {
  const requestArgs = {
    headers: { 'Authorization': `Bearer ${token}` },
    method: 'GET',
    uri: `${BASE_URL}/rest/V1/modules`,
    json: true
  }

  request(requestArgs, (err, msg, resp) => {
    if (err) {
      return cb(err) // library error
    }
    return cb(null, resp)
  })
}

From reading various articles and the Sinon documentation, it sounds like I might possibly need a "spy" or a "mock" for request()? Even if I faked the external API call with a good response, what good does it do if it always returns a good response since all this method does is put together requestArgs and return the external call's response. I'm confused with the terms "stub", "spy", and "mock" and what I need to do for this wrapper method.

laketuna
  • 3,832
  • 14
  • 59
  • 104
  • See this SO question for differences between a Mock, Stub and Spy https://stackoverflow.com/questions/24413184/can-someone-explain-the-difference-between-mock-stub-and-spy-in-spock-framewor – bentesha Sep 15 '17 at 16:10

1 Answers1

1

See this SO question for differences between a Mock, Stub and Spy object.

Can someone explain the difference between Mock, Stub, and Spy in Spock framework testing and when to use them?

In your Unit Tests, you should always limit the scope of your test to only that particular unit that is being tested. In your case, I would stub the "request" function, and return the whatever data I would expect to be returned in different scenarios.

This approach offers a number of advantages, including speeding up your tests. Accessing external resources is usually time consuming. In addition, since your test has been narrowed down to a much smaller scope, it becomes a lot easier to pinpoint a problem.

If the scope of your test included more that one unit, then that would be considered an integration test. An integration test intends to check the flow of communication between various units and the flow of data between them.

Even if I faked the external API call with a good response, what good does it do if it always returns a good response

You should test your units in as many different scenario as possible, to make sure you code behaves correctly in every situation you might run into.

Do you receive the correct arguments in the callback function in every scenario? Whether an error is returned or not?

Think of your tests as a live documentation of your code. Your tests should describe what your code is supposed to do.

If another developer, for instance, makes a breaking change, or you accidentally introduced a bug while refactoring your code, your test should be able to catch it.

bentesha
  • 898
  • 9
  • 14