Mocking Objects in React’s Test

Source: https://dev.to/destro_mas

This article is written as a part of Individual Review of Fasilkom UI’s Software Engineering Project Course 2021

Mock the API!

What is Mocking?

Mocking in ReactJS with Jest

post function in http.js (tested)
Create test for login function with Jest.
Test is failed because we haven’t implemented the login function yet.
Implementation of login function.
The test is passed with 100% coverage.

Mocking Test in Software Engineering Project Course 2021

get function in http.js (tested)
Create test for getAllTransactions function with Jest.
Test is failed because we haven’t implemented the getAllTransactions function yet.
Implementation of getAllTransactions function.
The test is passed with 100% coverage.

Bonus: Mocking vs Stubbing?

const purchaseItemsFromCart = (cartItems, user) => {
let payStatus = user.paymentMethod(cartItems)
if (payStatus === "success") {
user.sendSuccessMail()
} else {
user.redirect("payment_error_page")
}
}

}
// Stubbing
"when purchase payed successfully user should receive a mail" : function() {
// Setup
let paymentStub = sinon.stub().returns("success")
let mailStub = sinon.stub()
let user = {
paymentMethod: paymentStub,
sendSuccessMail: mailStub
}

// Exercise
purchaseItemsFromCart([], user)

// Verify
assert(mailStub.called)
}
// Mocking
"when purchase payed successfully user should receive a mail" : function() {
// Setup objects
let userMock = sinon.mock({
paymentMethod: () => {},
sendSuccessMail: () => {}
})

// Setup expectations
userMock.expect(paymentMethod).returns("success")
userMock.expect(sendSuccessMail).once()

// Exercise
purchaseItemsFromCart([], user)

// Verify mocks
userMock.verify()
}

My Thoughts

Currently studying at Faculty of Computer Science, Universitas Indonesia.