Why is the expect (ember-mocha) doesn't run in ember-mirage route?

  it('check request \'by\' query param', async function() {
    this.by = 'gender';

    this.server.get('/patients/stats', (_schema: any, request: any) => {            
      expect(request.queryParams.by).to.equal(this.by + 'sdfdg');
      
      return {
        items: [
          {
            label: 'Male',
            count: 157
          },
          {
            label: 'Female',
            count: 144
          }
        ],
        meta: {
          total: 301
        }
      }
    });

    await render(hbs`<Patients::Stats @by={{this.by}} />`);
  });

The expect(request.queryParams.by).to.equal(this.by + 'sdfdg'); should not pass the test because the query param (request.queryParams.by) is equal to ‘gender’. But the test somehow still passed…

I would guess that the test is finishing before your expectation actually evaluates. To be sure we’d need to know more about how your <Patients::Stats> component is doing the data fetching.

1 Like

This is just a simple fetch in the components constructor and fetching the '/patients/stats' endpoint with the query param 'by' what I pass to the component as an argument. In this case it is look like this: '/patients/stats?by=gender'. This should return a JSON object like in the example.

Right, so the fetch is running asynchronously and there’s nothing to make the render or the test wait for it to finish before moving on.

The simplest change to fix your test is probably to use something like waitFor to wait until your content appears in the DOM. You’d do this after await render().

That way the test won’t end until after your component has had a chance to actually run the whole fetch, which should cause the side-effect of hitting your expectation.

1 Like

The waitFor is not helped, because the problem is I don’t get back this data from this endpoint. When I comment out expect(request.queryParams.by).to.equal(this.by + 'sdfdg'); this line I got back the data but I don’t how to check the request param. :roll_eyes:

Ah, so I think you’re being bitten by the way mocha handles failures. It throws an exception, which in this case will probably get caught by mirage.

Instead of putting the expect() inside the mirage handler, try just storing the queryParam:

it("check request 'by' query param", async function() {
    this.by = 'gender';
    let gotQueryParam;

    this.server.get('/patients/stats', (_schema: any, request: any) => {        
      gotQueryParam = request.queryParams.by;
      
      return {
        items: [
          {
            label: 'Male',
            count: 157
          },
          {
            label: 'Female',
            count: 144
          }
        ],
        meta: {
          total: 301
        }
      }
    });
    await render(hbs`<Patients::Stats @by={{this.by}} />`);
    expect(gotQueryParam).to.equal(this.by + 'sdfdg');
  });
1 Like

It’s working! Thank you so much for your time and help! :grin: