I could use some help to find a solution for my problem. I need to mock some data to my angular2 application when it makes a request to an api, I need to do something like:<
I found a solution to this that is relatively painless and so far works great, and doesn't require you changing all the references to your existing imports.
There are several steps depending on what you are trying to accomplish. I was working on e2e tests, so this will outline that solution.
First update your angular.json with configs that are specific to your test environment, (right above "serve") mine is:
"serve-e2e": {
builder: '@angular-devkit/build-angular:dev-server',
options: {
browserTarget: '{APP_NAME}:build'
},
configurations: {
test: {
browserTarget: '{APP_NAME}:build:test'
}
}
};
Then, update your existing e2e config by updating the devServerTarget with your new config:
"devServerTarget": "{APP_NAME}:serve-e2e:test"
Next I created a new set of environment specific files called mock-service-mapping, so in my environment folder I now have:
mock-service-mapping.ts
mock-service-mapping.test.ts
In these files, I store the mapping to my real and mock services:
import { RealDataService } from '../app/lib/services/real-data.service';
export const mockServiceMapping = {
dataServiceClass: RealDataService
};
Now we need to make them environment specific. Update your angular.json to setup the proper mappings for your different environments:
"test": {
fileReplacements: [
{
replace: 'src/environments/environment.ts',
with: 'src/environments/environment.test.ts'
},
{
replace: 'src/environments/mock-service-mapping.ts',
with: 'src/environments/mock-service-mapping.test.ts'
}
]
};
And the last piece of magic. In your module declarations, setup your providers to pull the class from your new mock environment files.
{ provide: DataService, useClass: mockServiceMapping.dataServiceClass }
And voila, mock services, no libraries, no mess, no extra compiled code, and fairly straightforward!