1

I have this method inside a class

class Stuff {
  constructor() {}

  createStuff(stuff) {
    const stuffStorage= [];
    storage.push(stuff);
    return stuffStorage;
  }
}

it("should push to stuff array", () => {
  // instantiate the class 
  const stuff = new p.product();
  stuff.createStuff();
  expect(stuff.createProduct("stuff")).toEqual(["stuff"])
})

The test is passing. At the moment the method does what the test tells it to do. Push stuff to an array. Since I am at the beginning, I wonder if there is a better way of going this. Maybe use mock, on the .push. Any suggestions, please?

Kinfol
  • 55
  • 1
  • 9
  • 2
    What do you mean to achieve by mocking `push`? If the contract is that the function returns an array of its inputs, then that's all you can test unless you're going into its implementation details or the method changes class state. Beyond that, I'm guessing this is just a stub class--you might want to [add more details and context about the actual problem you're trying to solve](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) because the example seems overly contrived. – ggorlen Dec 03 '19 at 23:53
  • 1
    Your test passes. It's a really simple function. Job done. – see sharper Dec 04 '19 at 01:53
  • 1
    Take a look at https://stackoverflow.com/questions/38181/when-should-i-mock – Lin Du Dec 04 '19 at 03:16
  • @ggorlen Thank you for the comment! I was looking in to suggestions. I did think I could be looking in to testing the push() implementation. I could use with some help on the syntax. push() = jest.js(); expect(push().mock.calls.length).toEqual(1); I am confused. But maybe this is a topic for another question or could be implemented in this question? – Kinfol Dec 04 '19 at 09:10
  • I wouldn't worry about the syntax. I'd zoom out and ask "why am I mocking `push`?" Until you have a really compelling reason to do so, don't even worry about mocking it. Again, I have no idea what your real code is or what it's supposed to achieve (the function `createStuff` is totally nonsensical as it stands), but the short answer is that there's almost certainly no gain at all in mocking an array function like `push`. The link above from slideshowp2 is very good, but read [this](https://stackoverflow.com/a/38260/6243352), not the accepted answer. – ggorlen Dec 04 '19 at 15:00
  • Thank you for your answers. It makes sense. I was going down the rabbit whole. – Kinfol Dec 21 '19 at 00:02

0 Answers0