Jasmine Spy not working with TestScheduler (I could use some help :-) #6025
Answered
by
cartant
antonkarsten
asked this question in
Q&A
-
I am writing a test for a service using TestSchedular and eventhough it is quite clear that my spy has been called, when i try to assert it it fails. I guess I am doing something wrong in the ordering or the way I write the test. Does anyone have an idea? I have made a simplified version of my service and test. You can try it out at : import { BehaviorSubject, Observable } from "rxjs";
import { scan, switchMap } from "rxjs/operators";
import { TestScheduler } from "rxjs/testing";
interface TransformService {
transform: (item: string) => Observable<string>;
}
class MyService {
items = new BehaviorSubject<string>(null);
constructor(private readonly transformService: TransformService) {}
addItem(item: string) {
this.items.next(item);
}
tranform(item: string) {
return this.transformService.transform(item);
}
getItems() {
return this.items.asObservable().pipe(
switchMap((item) => {
return this.tranform(item);
}),
scan((accumalation, item) => {
accumalation.push(item);
return [...accumalation];
}, [])
);
}
}
/**
* Test written with Jasmine Marbles
*/
describe("Main", () => {
let testScheduler;
let transformServiceSpy;
beforeEach(() => {
testScheduler = new TestScheduler((actual, expected) => {
expect(actual).toEqual(expected);
});
transformServiceSpy = jasmine.createSpyObj("TransformService", [
"transform",
]);
});
it("should transform the string", () => {
testScheduler.run((helpers) => {
const { cold, expectObservable } = helpers;
const transformResponse = cold("5000ms a", {
a: "transformed",
});
transformServiceSpy.transform.and.returnValue(transformResponse);
const service = new MyService(transformServiceSpy);
const expected = "5000ms a";
const values = {
a: ["hello"],
};
expectObservable(service.getItems()).toBe(expected, values);
service.addItem("transformed");
expect(transformServiceSpy.transform).toHaveBeenCalledTimes(1);
});
});
}); when I remove the following line it works expect(transformServiceSpy.transform).toHaveBeenCalledTimes(1); thank you very much !! |
Beta Was this translation helpful? Give feedback.
Answered by
cartant
Feb 14, 2021
Replies: 1 comment 1 reply
-
Read about flush();
expect(transformServiceSpy.transform).toHaveBeenCalledTimes(1); |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
antonkarsten
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Read about
flush
and call it before you make that assertion: