Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
    Peter Foeng
    @peterfoeng
    hi everyone, any pointers of mocking ActivatedRoute?
    2 replies
    Sergei Sergeevich
    @ssergdev
    Hello everyone! After update from 11.10.0 to 12.0.0 all spyes defined as
    mySpy = MockInstance(MyService, 'method', jasmine.createSpy()) just stop working. Is it not a valid way anymore?
    16 replies
    satanTime
    @satanTime

    Hi guys, I hope you all are well.

    If you don't mind, I would like to ask to support a fix in jest for ng-mocks with a like / upvote: facebook/jest#11483.

    Thank you in advance!

    satanTime
    @satanTime

    Hi everybody.

    v12.1.0 has been released.
    There is a potentially interesting feature for you besides stability improvements.
    It is MockRenderFactory, it allows to reuse the same middleware component in different tests. With its help and ngMocks.faster() you can get max performance.

    describe('Maximum performance', () => {
      const factory = MockRenderFactory(MyComponent, ['input1', 'input2']);
    
      ngMocks.faster();
      beforeAll(() => MockBuilder(MyComponent, MyModule));
      beforeAll(() => factory.configureTestBed());
    
      it('covers one case', () => {
        const fixture = factory({input1: 1});
        expect(fixture.point.componentInstance.input1).toEqual(1);
      });
    
      it('covers another case', () => {
        const fixture = factory({input2: 2});
        expect(fixture.point.componentInstance.input2).toEqual(2);
      });
    });
    satanTime
    @satanTime

    Hi everybody,
    I hope you are doing great.

    There is a big upcoming change regarding mocking platform root level definitions.
    Might you test a preliminary build of ng-mocks on your projects and let me know whether everything is fine?
    The build is here: https://github.com/ike18t/ng-mocks/files/6731063/ng-mocks.zip

    Thank you in advance and happy coding!

    Babeetlebum
    @Babeetlebum
    Hello, I want to mock a component but replace its template with a specific text, any easy way to do that with MockBuilder ? Something like MockBuilder(MyComponent, MyModule).mock(ComponentToStub, '<span>MY SPECIFIC TEXT</span>'); ? My first idea was to .replace() it with a stub which goes against the idea of ngMocksas I would have to maintain my stubs... Thanks for your help!
    11 replies
    satanTime
    @satanTime

    Hi everybody.

    12.4.0 has been released and it contains a braking change for those who use MockInstance inside of it.
    Now you need to configure it manually in the entry point file: https://ng-mocks.sudo.eu/extra/install#default-customizations

    Philip Lysenko
    @philly-vanilly
    Hi. I have a Component which I want to test (not mock). It has some public and private fields like destroy$ = new Subject(); which have no @Input. When I call MockRender and get the component via fixture.point.componentinstance, the fields are undefined. A console-log inside the constructor does also not get triggered. So wtf does MockRender do? Why does it not instantiate the component class in a proper way? Or am I using the lib in wrong way? Is this expected behavior?
    23 replies
    Vladislav
    @fleshka779
    Hi guys, Do you know this issue?
    ASSERTION ERROR: Expected localeId to be defined [Expected=> null != undefined <=Actual]
    2 replies
    Vladislav
    @fleshka779
    How can I mock with the MockBuilder ?
    @Optional() @Inject(A_SERVICE) private readonly aService: A_SERVICE,
    2 replies
    Philip Lysenko
    @philly-vanilly

    Hello again, I wanted to ask: what is the recommended way to mock a service for the whole test suite, so any function that is called can be spied on? Using mock() in MockBuilder does provide a mock, but it seems the public methods are regular functions, not of type jasmine.Spy or jest.fn(). You cannot spy on them.

    So I really need to define every method I want to spy on myself? Either by using provide(SomeService, useValue: { someMethod: jasmine..... }) or by mocking SomeService and using MockInstance on the methods I want to spy on, is that correct?

    Then, when I want to change the defaults I have set in beforeEach, I also use MockInstance? Or do I simply jasmine.spyOn(TestBed.inject(SomeService), 'someMethod', OVERRIDE). I don't fully understand MockInstance, it seems more complicated than jasmine.spyOn(TestBed.inject(...)) because you additionally need to take care of scopes, so is there something I am missing?

    6 replies
    John
    @jsmart523
    I'm evaluating ng-mocks And one of the stumbling points I felt was getting a strongly typed, mocked instance from TestBed.
    (sorry, 1st time, attempted to add paragraph and of course it sent instead. Continuing...) I saw getMockedNgDefOfbut that returns a Type<any> which is both anathema to what I'm looking for (because I want strongly typed, not any) And also I'm looking for the mocked and injected instance, not the class. I have written agetMockedInjected` For myself, and it works, but either it already exists and I'm just missing it in the documentation or I should submit a poll request to pay it forward and hopefully get it supported, right?
    3 replies
    John
    @jsmart523
    pull request 😐
    dasco144
    @dasco144

    Hi guys.
    I'm trying to test a route resolver and everything seems to be working fine for the successful resolve, but for unsuccessful resolves, I redirect the user to a different route using

                return from(
                    this.router.navigate(['app/maintenance'], { state: { tab } })
                ).pipe(map(() => null));

    The problem seems to be that when I check the location.path, it has not navigated to the route yet (Error: Expected '/' to equal '/app/maintenance'). I can also see in coverage that the map operator has not been hit at all, which leads me to believe that the router.navigate promise has not resolved yet when the test ends.
    I've tried multiple tick, flush, flushMicrotasks calls but I'm not able to get this router navigate to resolve.

    Can anyone assist with this?

    6 replies
    dabbid
    @dabbid

    Hello guys, I'm facing an issue while migrating component tests with ngMocks. This component has a component with some ng-content slots as dependency. Component's wrapping module declares schemas: [CUSTOM_ELEMENTS_SCHEMA] in its metadata to avoid rendering error like 'my-ng-content-slot-name' is not a known element:. In my tests, when I simply does this:

    beforeEach(() =>
      MockBuilder(MyComponent, MyModule)
        .keep(FormsModule)
        .keep(ReactiveFormsModule)
    );

    It logs the same rendering error. And same if I do something like this:

    beforeEach(() => {
      const ngModule = MockBuilder(MyComponent, MyModule)
        .keep(FormsModule)
        .keep(ReactiveFormsModule)
        .build();
      ngModule.schemas = [CUSTOM_ELEMENTS_SCHEMA];
      return TestBed.configureTestingModule(ngModule).compileComponents();
    });

    Does anyone has already faced and solved this kind of issue?

    dabbid
    @dabbid
    Mmm it doesn't seem to be related to any ng-content, but more to MarkdownModule (from ngx-markdown) mocking and a <code-pane>web component (I guess) that causes a rendering error if CUSTOM_ELEMENTS_SCHEMA is not declared. If I declare all using TestBed.configureTestingModule like below, it works:
    TestBed.configureTestingModule({
      declarations: [MyComponent],
      imports: [
        FormsModule,
        ReactiveFormsModule,
        MyModule,
        MockModule(MatFormFieldModule),
        MockModule(MatButtonToggleModule),
        MockModule(MatButtonModule),
        MockModule(MatMenuModule),
        MockModule(MatIconModule),
        MockModule(MarkdownModule),
      ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
    }).compileComponents()
    It seems that assigning ngModule.schemas = [CUSTOM_ELEMENTS_SCHEMA]; and then passing this ngModule to TestBed.configureTestingModule doesn't work
    2 replies
    Babeetlebum
    @Babeetlebum

    Hello, I'm trying to mock a service that is injected directly in a component like so

    @Component({
      selector: 'app-test',
      templateUrl: './test.component.html',
      styleUrls: ['./test.component.scss'],
      providers: [ProvidedInComponentService],
    })
    export class TestComponent {
      constructor(public providedService: ProvidedInComponentService) {}
    }

    but neither MockBuilder().mock(ProvidedInComponentService) nor MockInstance(ProvidedInComponentService, '...', ...) seem to work
    the real service is called instead
    I can provide a github repo with a reproduction if needed

    8 replies
    Matej Hudak
    @mathudak
    Hey guys,
    I'm facing some issues when I try mocking methods from generated API services (imported as a npm module). I created a github issue/question about: ike18t/ng-mocks#1191. It's little bit easier to read there
    Sergei Sergeevich
    @ssergdev
    Hello. "...MockRender cannot be used without a reset after TestBed.get...". According to this message, how should i get some instance from the injector, before MockRender is executed? What I'm trying to achieve is to mock some common services with ngMocks.defaultMock and then request the spyObj from the injector without jasmine.createSpyObj... duplication. Thanks for a great testing tool!
    4 replies
    satanTime
    @satanTime
    Hi all! Happy New Year! Thanks for reporting. I’ll try to get back to the business this weekend. Unfortunately, I got poisoned on 30.12 and had the worst new year ever :)
    Ivan
    @ivan1fun
    Hi!
    I haven't found anything about the detectChanges parameter of the MockRender method anywhere. Add it to the documentation, please
    2 replies
    satanTime
    @satanTime
    Hi. Thanks. I’ll do.
    Gulmariyam Yerzhanova
    @rzhnv:matrix.org
    [m]
    Hey everybody.I have just started writing FrontEnd Unit test. Now I found something new for me: ngmocks. I have a question: when is best to use ngmocks?
    1 reply
    Timo
    @Swamp3

    Hello, i am evaluating ng-mocks for our tests but i ran into a Problem. In one component i am trying to access the html-element of an input. I am then trying to trigger the focus event on this element but it does not seem to work.
    Error: Timeout - Async function did not complete within 5000ms (set by jasmine.DEFAULT_TIMEOUT_INTERVAL)

    This test worked without ng-mocks so i expect i am missing something?

    This is my setup of the test:

    beforeEach(() => {
            return MockBuilder(LoginComponent, AppModule)
                .keep(ActivatedRoute)
                .keep(RouterTestingModule);
        });
    
    it('should toggle form focus on input selection', async () => {
            fixture = MockRender(LoginComponent);
            component = fixture.componentInstance;
            const userInput = ngMocks.find('#userid');
            const focusSpy = spyOn(component, 'onFocus');
            expect(component.formFocus.value)
                .toBeFalse();
            // ngMocks.touch(userInput);
            ngMocks.trigger(userInput, 'focus');
            fixture.detectChanges();
            await firstValueFrom(component.formFocus.pipe(first(v => v)));
    [...]
    })
    11 replies
    Dixit Bafna
    @Dixit199213bafna
    1 reply
    Marvin Rensing
    @MetroMarv

    Hey guys,
    I'd like to know how I can always render a directive, when using the TestBed for my tests. When I use the MockBuilderI can do the following:

    return MockBuilder(TestedComponent).mock(MyStructuralDirective, {
           render: true, 
        });

    But if I use MockDirective(MyStructuralDirective) with the TestBed I cannot set render: true:

    TestBed.configureTestingModule({
            declarations: [
              MyComponentUnderTest,
              MockDirective(MyStructuralDirective),
            ],
            providers: [
              // ... some providers
            ],
          }).compileComponents();

    Can I somehow always render a structural directive together with a TestBed test setup?

    3 replies
    dasco144
    @dasco144
    Hi guys
    I have upgraded to Angular 13, and by extension ng-mocks 13.2.0, and some of my tests don't seem to be working any more. I think its to do with an angular change to the way the router activates the outlet. When comparing v12/v13 it looks like this line (https://github.com/angular/angular/blob/master/packages/router/src/directives/router_outlet.ts#L269) returns different results
    3 replies
    satanTime
    @satanTime

    Hi all,

    13.4.0 has been released.
    BrowserAnimationModule is optional now, also the release adds support to resplect mocks in vcr.createComponent.
    Please let me know your feedback.

    Elliot Wesoff
    @elliotwesoff

    Hi there, I get an error message when trying to mock a service that uses an observable. Following the guide here (https://ng-mocks.sudo.eu/extra/mock-observables), I get this error

    The last overload gave the following error.
        Argument of type '{ caseSubject: () => Subject<any>; }' is not assignable to parameter of type 'IMockBuilderConfig'.
          Object literal may only specify known properties, and 'caseSubject' does not exist in type 'IMockBuilderConfig'.

    I'm using a line like this:
    MockBuilder(...).mock(CaseService, { caseSubject: () => EMPTY })

    I'm able to squelch the error by telling the transpiler to chill out with .mock(CaseService, { caseSubject: () => EMPTY } as IMockBuilderConfig) but I don't think that's the right way to do it. Can anyone tell me if I'm doing this wrong? Thanks!

    1 reply
    ThijsBloksVolksbank
    @ThijsBloksVolksbank
    This message was deleted
    24 replies
    Harikrishnan KK
    @harikrishkk
    Hi All, a simple question regarding ng mocks with template driven forms - Anyone could have an opinion or two on this question that I have posted on stackoverflow? https://stackoverflow.com/questions/71984841/ng-mocks-library-to-test-form-component-template-driven-form
    30 replies
    sdomaradzki
    @sdomaradzki
    Hi All, I'm quite new to the ng-mocks and I have a problem with testing angular material's confirmation popup... How can I detect if angular material's confirmation popup was launched and how can I test if proper action has been triggered after confirm/cancel buttons has been pressed on such popup?
    1 reply
    Mark Clark
    @daerogami
    do defaultMocks only show up in tests setup with MockBuilder?
    3 replies
    Brandon Schreck
    @BrandonSchreck
    Are there any pro tips on mocking out a Component's private readonly rxjs Subject<void> property? My component is setup to retrieve data from the backend with takeUntil(this.destroying$) setup in the pipe stream. But when I run my tests, this.destroying$ is undefined.
    4 replies
    grimaldistudio
    @grimaldistudio
    it('should search on grid ', () => {
        const itemList = ngMocks.find(UiItemListComponent);
        expect(itemList).toBeTruthy();
        const qSearch = 'blog';
        const setSearch =  jest.fn();
    
        itemList.componentInstance.searchEvent.emit(qSearch);
        expect(component.searchTerm).toEqual(qSearch);
        expect(setSearch).toHaveBeenCalledTimes(1);
    
    
        //expect(setPageZero).toHaveBeenCalled();
      });

    Error: expect(jest.fn()).toHaveBeenCalledTimes(expected)

    Expected number of calls: 1
    Received number of calls: 0

    searchTerm is set correctly with the qSearch parameter inside the "real" setSearch function.
    Why is the mockata setSearch function not called?
    Thanks.

    8 replies
    Van Tigranyan
    @VanTigranyan
    CleanShot 2022-05-13 at 16.34.25@2x.png
    15 replies
    Hi everyone. Someone, please, help me understand where this MockInstance comes from?
    CleanShot 2022-05-13 at 16.39.34@2x.png
    Van Tigranyan
    @VanTigranyan
    @satanTime could you help me with one more thing? I am using ng-mocks alongside Spectator, and I stubbed one of my services. In one of my test cases I want to redefine the return value of a method of the service and then rerender the component to see if it works correctly. Basically I have no idea how to that, how should I get the mocked instance of the service and change the method, and then how do I trigger the rendering process? Attaching the screenshot of my test
    2 replies
    CleanShot 2022-05-16 at 15.31.21@2x.png
    Van Tigranyan
    @VanTigranyan
    @satanTime Sorry for so many questions. :D I have another one. How should I provide CUSTOM_ELEMENTS_SCHEMA to MockBuilder?
    4 replies
    Alex Al
    @alex_ro10_gitlab
    image.png
    Hi guys, I have a problem and I don't understand the error message, so basically I took an example from ng-mocks documentation and wanted to test the content of an ng-template, but I don't know what I am doing wrong here. I would appreciate any help and sorry for the inconvenience :)
    1 reply
    Alex Al
    @alex_ro10_gitlab
    @satanTime, but the MockBuilder does not create a mock component?
    BerrouMoustapha
    @BerrouMoustapha
    Hi All, a simple question regarding ng mocks : Can we use both MockProvider(to mock all functions of the service on beforeEach) and MockInstance(to specify the return of specific function on the test case) to mock a service ?
    7 replies
    satanTime
    @satanTime

    Hi all, ng-mocks@14 has been released. It supports standalone declarations, and MockBuilder lets you to mock their imports only.

    Please note that there is a breaking change in the version. If you've been using MockBuilder with 2 params, you might need to add export flag to some external dependencies: https://ng-mocks.sudo.eu/migrations#from-13-to-14

    Testing of standalone declarations:

    rlacatus
    @rlacatus

    Hi All - looking to test default value of a component using the suggested approach:
    (see : https://ng-mocks.sudo.eu/api/MockRender#empty-params)

    MockRender(MyComponent, {});

    I'm running into the following error:

    Type 'MockedComponentFixture<MyComponent, {}>' is not assignable to type 'MockedComponentFixture<MyComponent, DefaultRenderComponent<MyComponent>>'.

    Does this makes sense to anyone as to what the issue is?
    (note, seems to work fine when I give it some params to work with)

    1 reply
    Sergei Sergeevich
    @ssergdev
    Hello everyone! After updating ng-mocks from 12.5.1 to 14 I've got a lot of issues "MockBuilder has found a missing dependency...". Some of them are related to the ng-mocks@14 breaking change and fixed with onMockBuilderMissingDependency: 'i-know-but-disable'But others are not:
    Often it is an issue with "Router" or "MatDialogRef" or other services which is not provided by module: before the update it was working just like this: MockBuilder(TargetComponent, TargetModule).mock(Router) // .mock(Router, routerSpyObj) But now i must to set the second and third parameters with {precise:true} to the .mock() function which is not looking clear for me. How can we avoid confusing magic words when using MockBuilder and get back to the old simple ng-mocks@12 behavior? Thanks for continuously improving the project!
    14 replies