cccap1550
cccap1550

Reputation: 23

Unable to run mockttp with Cypress

I'm trying to run the mockttp with cypress. I used the example that's listed in project github. I changed the port to run on 3000 but I am getting an error saying Cannot add rules before the server is started.

/*global cy:true,before:true*/
/// <reference path="../../node_modules/cypress/types/index.d.ts" />

const superagent = require("superagent");
const mockServer = require("mockttp").getLocal();

describe('mockttp test' , () => {
    beforeEach(() => {
        mockServer.start(3000);
    });
    afterEach(() => {
        mockServer.stop();
    });
  it("lets you mock requests, and assert on the results", async () => {
    // Mock your endpoints
    const mockedPath = mockServer.forGet("/mocked-path");
    
    // ERROR OCCURS HERE
    await mockedPath.thenReply(200, "A mocked response");

    // Make a request
    const response = await superagent.get("http://localhost:3000/mocked-path");

    // Assert on the results
    expect(response.text).to.equal("A mocked response");
  });
});

Upvotes: 1

Views: 567

Answers (1)

Tim Perry
Tim Perry

Reputation: 13276

You need to wait until the server is actually started before running your test, by waiting for the promises returned by mockServer.start() (and by .stop()).

You can either make your beforeEach & afterEach functions async and then await those lines, or you can just add return to return the promise so that Mocha waits for them automatically.

Upvotes: 1

Related Questions