This repository is an example of service virtualization in an angular 6 application.
Service virtualization is the simulation of interfaces – not the virtualization of systems. Service virtualization lets you automatically execute tests even when the application under test’s dependent system components (APIs, third-party applications, etc.) cannot be properly accessed or configured for testing. By simulating these dependencies, you can ensure that your tests will encounter the appropriate dependency behavior and data each and every time that they execute. It’s commonly used when integration tests or end-to-end tests need to interact with dependent system components that are:
- Unreliable, evolving, or not yet completed
- Beyond your scope of control (e.g., operated by another company or division
- Available for testing only in limited capacity or at inconvenient time
- Challenging to provision or configure in a test environment
- Simultaneously needed by different teams with varied test data setup and other requirement
- Too restricted or costly to use for automated regression testing
# install dependencies
npm i
# run mountebank
npm run mb &
# serve the angular application on http://localhost:4200
npm run ng serve
After running these commands visit http://localhost:4200 and if all went well you should be greeted by the angular logo and a button "Fetch post". Click on that button and you might notice the following output in the terminal:
info: [https:4546 proxy] ::ffff:127.0.0.1:34894 => GET /posts/1Angular sends the HTTP Get /posts/1 via a webpack proxy towards Mountebank. Mountebank is configured to proxy traffic towards https://jsonplaceholder.typicode.com/ and store the response in a cache. Mountebank will serve the response from cache on future requests.
Service virtualization can aid development and also creates the stub files to use in tests.
To proxy requests towards mountebank from the webpack development server the src/proxy.conf.json file has been created and the following configuration has been added to the angular.json file:
{
"proxyConfig": "src/proxy.conf.json"
}To persist mountebank's cache to disk run the following command:
npm run mb-save
Service virtualization is a pain to set up in unit test because there are no build in utilities for Angular to wait on network latency. Angular does provide utilities to mock/stub services that use rxjs (the HttpClientModule for example) which is a lot easier to use.
Service virtualization is more suited for end to end testing. Unfortunately there is no way to easily use the same src/proxy.conf.json configuration as we use for development. To allow the same proxy behaviour we have added the following configuration to the src/karma.conf.js:
proxyValidateSSL: false,
proxies: {
'/posts': 'https://localhost:4546/posts'
}
});