mercredi 29 mai 2019

Jest test process never completing after all tests pass. How can I get them to complete

I have a Jest test class with 2 tests that are both passing fine. My problem is that when I run yarn run test my tests execute but Jest hangs. After digging around online I found a lot of people talking about not handling async/await correctly, but based on everything I see in the Jest docs my implementation is correct. I also tried running the tests with the flag --detectOpenHandles but it gives me no information. The last message I get in my console is "Ran all test suites." but it just hangs after that and never closes the test process. If I use the --forceExit flag is closes fine, but I don't want to have to use this. How can I get my tests to complete?

This is my test class:

describe('urlShortener middleware', () => {

  const LONG_URL = "www.google.com";
  const SHORT_URL = "www.g.com";

  let shortenUrl;

  const req = {
    body: {
      url: LONG_URL
    }
  };

  const res = { end: jest.fn(), json: jest.fn(), status: jest.fn().mockReturnThis() };

  const mockResponse = {
    body: {
      "short_url": SHORT_URL
    },
    status: 201  
  };

  let axiosMock = {
    post: jest.fn().mockResolvedValue(mockResponse)
  };

  beforeEach(() => {
    req.body = {url: LONG_URL};

    jest.setMock('axios', axiosMock);
    shortenUrl = require('../urlShortener').default;

    res.end.mockReset();
    res.json.mockReset();
    res.status.mockReset();

    res.status.mockReturnValue(res);
  });

  it('should return the data appropriately when nothing goes wrong', async (done) => {
    await shortenUrl(req, res);

    expect(axiosMock.post.mock.calls[0][1].original_url).toBe(LONG_URL);
    expect(res.status).toHaveBeenCalledTimes(1);
    expect(res.status).toHaveBeenCalledWith(201);
    expect(res.json).toHaveBeenCalledWith({ shortUrl: SHORT_URL });

    done();
  });

  it('should set the correct status when the world burns', async (done) => {
    axiosMock.post = jest.fn().mockRejectedValue(new Error());

    await shortenUrl(req, res);

    expect(res.status).toHaveBeenCalledTimes(1);
    expect(res.status).toHaveBeenCalledWith(500);
    expect(res.json).toHaveBeenCalledTimes(1);

    done();
  });
});

Aucun commentaire:

Enregistrer un commentaire