在所有测试通过后,笑话测试过程永远不会完成。我如何让他们完成

时间:2019-05-29 20:53:38

标签: javascript unit-testing testing automated-tests jestjs

我有一个Jest测试类,其中有2个测试都通过了。我的问题是,当我运行yarn run test时,我的测试会执行,但Jest会挂起。在网上闲逛之后,我发现很多人都在谈论不能正确处理异步/等待,但是基于我在Jest文档中看到的所有内容,我的实现是正确的。我还尝试了使用--detectOpenHandles标志运行测试,但是它没有任何信息。我在控制台中收到的最后一条消息是“运行所有测试套件”。但此后它只会挂起,并且永远不会关闭测试过程。如果我使用--forceExit标志可以很好地关闭,但是我不想使用它。我怎样才能完成测试?

这是我的测试课:

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();
  });
});

0 个答案:

没有答案
相关问题