Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

128
Views
How to test a callback functionality in a nested code

For explicitness to knowing how to write tests for my existing code, I am keeping not-so-good code. How to test this...

const saveProducts = () => {
 arr = [
    {
        name: "Mini Tiffin",
        category: "Kitchen",
        description:
            "kadai",
        price: 399,
    },
    {
        name: "Big Boy Burger",
        category: "American",
        description: "Double patty burger with cheese and fries",
        price: 500,
    },
];

    arr.forEach(function (item, req, res) {
        productImg = saveProductImg();

        return Product.findOne({ name: item.name }, (err, data) => {
            if (!data) {
                try {
                    const newProd = new Product({
                        name: item.name,
                        description: item.description,
                        price: item.price,
                        category: item.category,
                        productImg: productImg,
                    });
                    newProd.save();
                } catch (err) {
                    console.log(err);
                }
            }
        });
    });
};

This is failing. (saveProducts is module.exported)

        it("Save should be called two times", async (done) => {
            // Arrange
            const arrMock = [{name: 'one'}, {name: 'two'}];
            const revert = productController.__set__("arr", arrMock);

            const findOneMock = sinon.stub(Product, "findOne").resolves(undefined);
            const saveMock = sinon.stub(Product.prototype, "save");
            // findOneMock.returns(sinon.promise().resolves(undefined));

            await productController.saveProducts();
            expect(saveMock).to.have.been.called;

            done();
        });
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!