I'm trying to test this particular function of my component, it calls a service, then sets the new state. Pretty straight forward.
This is the function:
onProductAdded = async ({productId}) => {
const response = await ProductService.getProductById(productId);
if (response.length) {
const items = [...this.state.items];
items.push(response[0]);
this.setState({items});
}
}
And this is how I'm trying to test it:
describe('when cart is toggled and product is added', () => {
let wrapperInstance;
beforeEach(() => {
jest.mock("../../services/product-service", () => {
const data = [{
id: 1,
thumbnail: 'image_thumbnail.png',
title: `Product Name`,
price: 9.99
}];
return {
getProductById: jest.fn(() => Promise.resolve(data))
};
});
wrapperInstance = wrapper.instance();
wrapperInstance.onProductAdded({id: 1});
wrapperInstance.toggleCartDropdown();
});
test('should add one product', () => {
expect(wrapper.find('.Cart-counter').text()).toEqual('1');
});
test('should show 9,99 as total price', () => {
expect(wrapper.find('.js-totalPrice').text()).toBe('9.99');
});
});
I tried converting the test to async, tried using setImmediate(), tried doing wrapper.update().find() to try to update the dom, but nothing worked. When I try to print current component state after doing the call, the items array is still empty.
The errors I'm getting are: 1st test:
expect(received).toEqual(expected) // deep equality
Expected: "1"
Received: "0"
2nd test:
when cart is toggled and product is added › should show 9,99 as total price
Method “text” is meant to be run on 1 node. 0 found instead.
How can I make this test work?
Aucun commentaire:
Enregistrer un commentaire