'Trying to mock service property value
I'd like to mock the value of a service property my component uses. I can't seem to get the value to change however.
The problem I'm having is getting the component to use my new value. It's still using the 'https://stackoverflow.com' value from my service.
Component
import { ConfigService } from 'src/app/services/config/config.service';
@Component({
selector: 'app-some',
templateUrl: './some.component.html',
styleUrls: ['./some.component.scss'],
})
export class SomeComponent implements OnInit {
newURL: string;
constructor() {}
ngOnInit() {
...
}
changeURL() {
this.newURL = ConfigService.URL;
}
}
Service
@Injectable({
providedIn: 'root',
})
export class ConfigService {
public static URL = 'https://stackoverflow.com';
}
Spec
describe('SomeComponent', () => {
let component: SomeComponent;
let fixture: ComponentFixture<SomeComponent>;
const configServiceSpy = jasmine.createSpyObj(ConfigService, ['VERSION']);
beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule, LoggerTestingModule, IonicModule],
declarations: [SomeComponent],
}).compileComponents();
})
);
beforeEach(() => {
fixture = TestBed.createComponent(SomeComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should check if update is available', () => {
component.changeURL();
expect(component.newURL).toEqual('https://stackoverflow.com');
// Now I'd like to mock this service property
configServiceSpy.URL = 'https://google.com';
component.changeURL();
expect(component.newURL).toEqual('https://google.com');
});
});
Solution 1:[1]
Why don't you change it directly?
let backup = '';
beforeEach(() => backup = ConfigService.URL);
afterEach(() => ConfigService.URL = backup);
// ...
it('should check if update is available', () => {
// ...
ConfigService.URL = 'https://google.com';
// ...
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | satanTime |
