Home > Enterprise >  create invalid JSON for negative test in Typescript
create invalid JSON for negative test in Typescript

Time:12-30

I'm finding it difficult to work around TS (fantastic) static typing to create some invalid data for input to a negative test case.

I am trying to fix an error where invalid JSON (double quotes in the value) can be passed from the client. I have it fixed, but want to be assured of such in a unit test.

So I want to call a method with some invalid JSON to check that bad data will be rejected.

    postId: "1234",
    comment: "an invalid "comment"
  };

Can anyone help me find a way to write the test data to replicate the invalid JSON?

//ts-ignore 

isn't helping me. I know I am missing something obvious. TIA

Playground at https://codesandbox.io/s/competent-glitter-q8jn7

CodePudding user response:

Parsing args as JSON will always evaluate to true because JS objects are JSON serializable. So you can modify your function to the following and it should get the job done.

function acceptComment(args: MyBespokeMutationArgsType): boolean {
  if (!isJsonString(`{ "comment": "${args.comment}" }`)) return false;
  console.log("comment will be processed");
  return true;
}

And speaking of passing invalid input, you can use template strings.

const input = {
  postId: "1234",
  comment: `valid "comment`
};
  • Related