spectator
spectator copied to clipboard
mocking an injection token with different values
I'm submitting a...
[ ] Regression (a behavior that used to work and stopped working in a new release)
[ ] Bug report
[ ] Performance issue
[ ] Feature request
[ ] Documentation issue or request
[X] Support request
[ ] Other... Please describe:
Current behavior
I read your great medium article on using injection tokens, but I'm not entirely clear on how to test properly with spectator. I implemented the example shown below which I think is the correct way to test when the value doesn't change. Where I'm struggling now is that for each test in the file, I'd like to have different values for the injection token, but I can't figure out how to do that properly.
Minimal reproduction of the problem with instructions
https://codesandbox.io/s/elated-glade-bqzi6
Environment
Angular version: 12.2.5
Browser:
N/A
For Tooling issues:
- Node version: v12.19.0
- Platform: Windows
Others:
I know this is quite old, but I stumbled over this while googling and as I udnerstand the question, doing this in each test would help:
it('', () => {
spectator = createComponent({
providers: [
providers: [
mockProvider(RoomService, { room$: <MockValueHere>)
})
]
],
});
.... test it
});
You cannot call createComponent in the beforeEach hook anymore, but this way you can determine what the RoomService#room$
result should be for each tests. If you are dependent on Observable results in constructor/ngOnInit code, this is the only way afaik.
let spectator: Spectator<AppComponent>;
let component: AppComponent;
let roomService: SpyObject<RoomService>;
const createComponent = createComponentFactory({
component: AppComponent,
detectChanges: false,
mocks: [RoomService]
});
beforeEach(() => {
spectator = createComponent();
component = spectator.component;
roomService= spectator.inject(RoomService);
});
it("should do something", () => {
roomService.room$.andReturn(of(new RoomDetailsDTO()));
spectator.detectChanges();
// do your test
});
Or depending on your needs, you could also break the automatic detection changes, setting it to false, globaly mock the service, and then in each test, overriding this mock to return the desired mocked value and manually detecting changes.