2

I am trying to unit test a component that uses custom pipe. I want to provide a fake implementation of transform method for my test.

I have found that it is possible to override components, modules, pipe, etc., but I don't see how it is possible to override the behavior (implementation) of component.

I have tried to provide me custom class as a replacement for pipe and it didn't work:

TestBed
  .configureTestingModule({declarations: [MyPipe]})
  .overridePipe(MDatePipe, {set: MyFakePipe})

I have found similar question on SO How to mock Pipe when testing Component, but suggested solution was to create complete new pipe and provide it to declarations of testing module which is a bit too much in my opinion.

If overridePipe won't allow me to override transform implementation would it be possible to get instance of created MyPipe class and spyOn it?

var pipe = TestBed.get(MyPipe);

didn't work either.

Andrii Litvinov
  • 12,402
  • 3
  • 52
  • 59

1 Answers1

1

I haven't found a way to override the behavior of the Pipe so I ended up providing fake service to the real Pipe so that I can mock it's behavior.

Alternative solution would be to create fake pipe implementation for the test as suggested in answer to question How to mock Pipe when testing Component.

Andrii Litvinov
  • 12,402
  • 3
  • 52
  • 59
  • Still any ideas how to do this? =) – Sharikov Vladislav Aug 22 '17 at 21:58
  • @SharikovVladislav, that's basically how I did. My Pipe uses service and I fake the service to define behavior of the Pipe. Alternative solution during my research was to create a fake pipe in the test and register it with the same name. Which might also work well, but requires a bit more work. – Andrii Litvinov Aug 23 '17 at 05:52
  • I tried this: `Alternative solution during my research was to create a fake pipe in the test and register it with the same name`. That does not work. – Sharikov Vladislav Aug 23 '17 at 11:21
  • Here is what I tried: https://github.com/sharikovvladislav/ng2-diary-book/pull/41/commits/923f766185aaf977fe27b87f7a0ae72f11b84911. And here you can find red CI build: https://circleci.com/gh/sharikovvladislav/ng2-diary-book/103?utm_campaign=vcs-integration-link&utm_medium=referral&utm_source=github-build-link. I still get wrong timezone. – Sharikov Vladislav Aug 23 '17 at 11:22
  • I also tried to mock whole components and used `overrideComponent` method. I got the idea: I can change metadata of inner angular DatePipe. I can change name and I can load my own FakeDatePipe. Perhaps this will work. I will try a bit later. – Sharikov Vladislav Aug 23 '17 at 11:24
  • @SharikovVladislav solution you referenced does not sound quite right. I think you should do create your own `FakeDatePipe`. I have updated my answer with a link to another answer. – Andrii Litvinov Aug 23 '17 at 11:52