loopbackio / loopback-next

LoopBack makes it easy to build modern API applications that require complex integrations.
https://loopback.io
Other
4.95k stars 1.07k forks source link

Test examples with REST datasource (stub provider) #2185

Open rywilson28 opened 5 years ago

rywilson28 commented 5 years ago

My controllers are using a service provider that uses a REST datasource. This pulls in data from a remote server and then the controller manipulates this data to send to the client. I'm trying to find the best way to mock the responses from the remotes service in order to test the controller.

The documentation has a section for stub services but it is not currently populated. https://loopback.io/doc/en/lb4/Testing-your-application.html#create-a-stub-service

Can you please point me in the right direction.

rahulrkr08 commented 5 years ago

Hi @rywilson28,

I have created a sample rest application which has the test cases checking with mock service. Hope it may help you.

https://github.com/rahulrkr08/lb4-rest-sample

Thanks,

bajtos commented 5 years ago

When testing services, we advocate for using integration tests with a caching proxy to speed them up. The downside of writing stub services is that these services can easily get out of sync with the actual service implementation. See https://loopback.io/doc/en/lb4/Testing-your-application.html#test-your-services-against-real-backends.

Maybe I misunderstood your question?

If your goal is to test controllers in isolation and use a mocked service instance, then I would recommend to use https://sinonjs.org and stub the service the same way as you are stubbing repositories.

See our Todo example app for inspiration:

https://github.com/strongloop/loopback-next/blob/ce74b80c81ee16ea1239e2382f0dd0c29621e6ed/examples/todo/test/unit/controllers/todo.controller.unit.ts#L21

https://github.com/strongloop/loopback-next/blob/ce74b80c81ee16ea1239e2382f0dd0c29621e6ed/examples/todo/test/unit/controllers/todo.controller.unit.ts#L37

https://github.com/strongloop/loopback-next/blob/ce74b80c81ee16ea1239e2382f0dd0c29621e6ed/examples/todo/test/unit/controllers/todo.controller.unit.ts#L170-L173

bajtos commented 5 years ago

@rywilson28 @rahulrkr08 would you like to contribute and improve our documentation yourself? See https://loopback.io/doc/en/contrib/doc-contrib.html to get started.