DEV Community

Discussion on: How would you refactor this JS function?

Collapse
 
ksaaskil profile image
Kimmo Sääskilahti

Excellent answer, I like that you got rid of the boolean argument.

Now I'm only waiting for someone to write unit tests, in my world those are written before refactoring :)

Collapse
 
sargalias profile image
Spyros Argalias

Good suggestion :)

Collapse
 
rkallan profile image
RRKallan
it("should handle parent", () => {
    const textLinesAsArray = ["line 1", "line 2", "", "line 4"];

    const expectedValue = ["<h1>line 1</h1>", "<p>line 2</p>", "<p></p>", "<p>line 2=4</p>"];
    const resultValue = parent(textLinesAsArray);

    expect(resultValue).toEqual(expect.arrayContaining(expectedValue));
    expect(expectedValue).toEqual(expect.arrayContaining(resultValue));
    expect(resultValue.length).toEqual(expectedValue.length);
});

it("should handle toHtmlHeading", () => {
    const value = "Heading title";

    const expectedValue = "<h1>Heading title</h1>";
    const resultValue = toHtmlHeading(value);

    expect(resultValue).toEqual(expectedValue);
});

it("should handle toHtmlParagraph", () => {
    const value = "Paragraph text";

    const expectedValue = "<p>Paragraph text</p>";
    const resultValue = toHtmlParagraph(value);

    expect(resultValue).toEqual(expectedValue);
});
Enter fullscreen mode Exit fullscreen mode

didnt test these but i think this would be a start for testing.

And it's a choice TDD or BDD. It all depends on application. preferred working approach,
And in this case the question is to refactor the code. Basically there would be no need to change the tests. Still you will insert same input and would expect the same output

Except 2 or 3 solutions added new functions. So only on that case you would write new test