Reputation: 241
I know how to mock a function from a dependency, but now I have one function that is not in a dependency, it's in the actual component that I want to test. How can I tell jasmine to simply ignore it?
When I run ng test
this test fails:
The reason for this is this function that I import from an external library:
import { documentToHtmlString } from '@contentful/rich-text-html-renderer';
(Contentful is a content managament service that I use in my project.)
In my component this function gets called here:
ngOnInit() {
//the next line keeps the test from creating, I don't really care to test this function, how can I mock it?:
this.serializeContentfulRichText(someContentfulTextDoesntMatter);
// a lot more stuff that I actually need to test
...
}
serializeContentfulRichText(contentfulText: any) {
return documentToHtmlString(contentfulText, this.myRenderingOptions);
}
When I delete the documentToHtmlString
line and just return null the rest of the test works and I can test my whole component. But of course I can't just delete this line in my actual component, I just want to ignore/mock it in my test.
I tried it with a spy:
it('should create', () => {
let spy = spyOn(component, 'serializeContentfulRichText')
expect(spy).toHaveBeenCalledTimes(1)
expect(component).toBeTruthy();
});
But the spy doesn't get called and the component doesnt get created (Both expectations fail).
Upvotes: 4
Views: 5905
Reputation: 13539
If you want to stub a method of a testing component, you need to do it after TestBed.createComponent
, but before fixture.detectChanges()
.
In this case, only constructor of the component has been executed, but not lifecycle hooks.
it('should create', () => {
// initialization
const fixture = TestBed.createComponent(DeclarationScrolltextComponent);
const component = fixture.componentInstance;
expect(component).toBeTruthy();
// installing spies
const spy = spyOn(component, 'serializeContentfulRichText');
// executing render
fixture.detectChanges();
// assertions
expect(spy).toHaveBeenCalledTimes(1);
});
Upvotes: 3