Skip to content

Instantly share code, notes, and snippets.

@horsfallnathan
Last active August 20, 2020 08:44
Show Gist options
  • Save horsfallnathan/1810dfb63083e51d7db159786f1cbaba to your computer and use it in GitHub Desktop.
Save horsfallnathan/1810dfb63083e51d7db159786f1cbaba to your computer and use it in GitHub Desktop.
Get jest testing help

I have a simple Node application that takes form data from a website and saves to a Google sheets document. Wrote this some time back and now I am trying to write tests for it.

I have the submit function which is called when the client visits the '/submit' post route. Its content are:

// submit.routes.js

function Submit(req, res, next) {
  const { data, token } = req.body;
  const url = `https://www.google.com/recaptcha/api/siteverify?secret=${secret_key}&response=${token}`;

  axios(url, {
    method: "post",
  })
    .then((response) => {
      return response.data;
    })
    .then((response) => {
      if (response.success !== true) {
        console.log("err");
        throw new Error("captcha failed");
      }
    })
    .then(() => {
      schema.isValid(data).then(() => {
        updateSheet(data)
          .then(() => {
            res.json("Form submitted successfully");
          })
          .catch((err) => {
            res.status(504).send("error with submission");
          });
      });
    })
    .catch((err) => {
      res.status(504).send("error with form input or captcha");
    });
}

So far my test looks like this: // submit.spec.js

// First part 
describe("Check captcha", () => {
  it("captcha verification was successful", async () => {
    const res = { success: true };
    axios.get.mockImplementationOnce(() => Promise.resolve(res));
  });
  it("captcha verification failed", async () => {
    let errMessage = "Network Error";
    axios.get.mockImplementationOnce(() =>
      Promise.reject(new Error(errMessage))
    );
  });
});

// Second Part
describe("submit and update form", () => {
  it("should update google sheet", async () => {
    const update = { updateSheet: jest.fn() };
    res = { message: "Form submitted successfully" };
    req = {
      body: {
        name: "James", //Full object according to yup schema
      },
    };
    update.updateSheet.mockReturnValue(res);

    const result = await Submit(req);
    expect(result).toEqual(res);
    expect(update.updateSheet).toHaveBeenCalledTimes(1);
  });
});

So I'm missing the link between the capthca verification and schema validation -> schema.isValid before making the updateSheet test.

This is the link to the Repo

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment