question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Unable to use mocks with angular TestBed

See original GitHub issue

Love the simplicity of lib but im unable to use it in component testing with angular TestBed.

Test:

describe('FilterContentWidgetComponent', () => {
    let component: FilterContentWidgetComponent;
    let fixture: ComponentFixture<FilterContentWidgetComponent>;

    let filterMapperMock = Substitute.for<FilterMapper>();
    
    beforeEach(async() => {
        TestBed.configureTestingModule( {
            declarations: [ 
                FilterContentWidgetComponent,
            ],
            imports: [ HttpModule], 
            providers: [ 
                { provide: FilterMapper, useValue: <FilterMapper>filterMapperMock},
                
             ]
        }).compileComponents();
    });

    beforeEach(() => {
        fixture = TestBed.createComponent(FilterContentWidgetComponent);
        component = fixture.componentInstance;
      });

    it('should create', () => {
        fixture.detectChanges();

        expect(component).toBeTruthy();
    });
});

Not sure if am doing sth wrong but i get following exception.

TypeError: Cannot convert object to primitive value at JitEmitterVisitor._emitReferenceToExternal (http://localhost:9876/node_modules/@angular/compiler/fesm2015/compiler.js?:4693:44) at JitEmitterVisitor.visitExternalExpr (http://localhost:9876/node_modules/@angular/compiler/fesm2015/compiler.js?:4662:1) at ExternalExpr.visitExpression (http://localhost:9876/node_modules/@angular/compiler/fesm2015/compiler.js?:1293:1) at visitAllObjects.expr (http://localhost:9876/node_modules/@angular/compiler/fesm2015/compiler.js?:4387:1) at JitEmitterVisitor.visitAllObjects (http://localhost:9876/node_modules/@angular/compiler/fesm2015/compiler.js?:4406:1) at JitEmitterVisitor.visitAllExpressions (http://localhost:9876/node_modules/@angular/compiler/fesm2015/compiler.js?:4387:1) at JitEmitterVisitor.visitInvokeFunctionExpr (http://localhost:9876/node_modules/@angular/compiler/fesm2015/compiler.js?:4218:1) at JitEmitterVisitor.visitInvokeFunctionExpr (http://localhost:9876/node_modules/@angular/compiler/fesm2015/compiler.js?:4547:1) at InvokeFunctionExpr.visitExpression (http://localhost:9876/node_modules/@angular/compiler/fesm2015/compiler.js?:1250:1) at visitAllObjects.expr (http://localhost:9876/node_modules/@angular/compiler/fesm2015/compiler.js?:4387:1)

Issue Analytics

  • State:open
  • Created 5 years ago
  • Reactions:2
  • Comments:15 (10 by maintainers)

github_iconTop GitHub Comments

1reaction
DamienBraillardcommented, May 10, 2019

I got a workaround that allows to inject substitutes as providers using the TestBed.

Defining the substitute provider resolution by value (‘useValue’) like this does not work indeed:

//
// Not working example because the provider is resolved by 'useValue'
//
describe('My test', () => {
  let sampleListService: SubstituteOf<SampleListService>();

  beforeEach(() => {
      sampleListService = Substitute.for<SampleListService>();

      TestBed.configureTestingModule({
        declarations: [ SampleListComponent ],
        providers: [
            { provide: SampleListService, useValue: sampleListService }
        ]
      })
      .compileComponents();
    });
});

But… what works is to setup the provider resolution by factory like that:

//
// Working example because the provider is resolved by 'useFactory'
//
describe('My test', () => {
  let sampleListService: SubstituteOf<SampleListService>();

  beforeEach(() => {
      sampleListService = Substitute.for<SampleListService>();

      TestBed.configureTestingModule({
        declarations: [ SampleListComponent ],
        providers: [
            { provide: SampleListService, useFactory: () => sampleListService }
        ]
      })
      .compileComponents();
    });
});

For the sake of brievety:

Replace

{ provide: SampleListService, useValue: sampleListService }

By

{ provide: SampleListService, useFactory: () => sampleListService }

And it should work. I’m using Jest as test framework with Angular 7.

Hope it helps !

1reaction
ffMathycommented, Apr 29, 2019

It sure does @Karql! I’ll take a look as soon as I have the time. Won’t be for the next month or so I think.

I think I’ll end up creating different integrations for substitute.js, for instance @fluffy-spoon/substitute-angular, which you can then “hook in” to substitute.js to support these cases.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Angular2 Unit Test Not Using Mock Service - Stack Overflow
I had 2 services in my component I needed to mock for testing. One (let's call it MyService ) was successfully using a...
Read more >
All You Need to Know About Mocking in Angular Tests (2020)
For mocking component, the easiest solution I have found is to avoid needing to mock components by shallow testing, that is, use schemas:...
Read more >
The correct way of mocking dependencies in the Angular unit ...
Solution. The code above shows a simple and quick solution. You can create a mock class that extends the UserService . Then you...
Read more >
Using Stubs and Mocks in Jasmine to test your Angular code
Setting up your environment and is a very important part of unit testing AngularJS code. We discuss some of the tools and methods...
Read more >
How to update to the latest version of ng-mocks
If you call MockBuilder with 2 parameters and use the chain for dependencies: ... Likewise, an Angular application would fail too.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found