[英]React.js - Simulating a click with Enzyme
我有這個React.js應用程序,這是一個簡單的購物車應用程序。 https://codesandbox.io/s/znvk4p70xl
問題是我試圖使用Jest和Enzyme對應用程序的狀態進行單元測試,但它似乎不起作用。 這是我的Todo.test.js
單元測試:
import React from 'react';
import { shallow, mount, render } from 'enzyme';
import Todo from '../components/Todo';
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });
test('Test it', async () => {
// Render a checkbox with label in the document
const cart = [
{ name: 'Green', cost: 4 },
{ name: 'Red', cost: 8 },
{ name: 'Blue', cost: 14 }
];
const wrapper = mount(<Todo cart={cart} />);
const firstInput = wrapper.find('.name');
firstInput.simulate('change', { target: { value: 'Pink' } });
const firstCost = wrapper.find('.cost');
firstCost.simulate('change', { target: { value: 200 } });
const submitButton = wrapper.find('.addtocart');
submitButton.simulate('click');
wrapper.update();
expect(wrapper.state('price')).toBe(26);
console.log(wrapper.state());
console.log(wrapper.props().cart);
});
當我進行測試時,當應該添加Pink
項目時,購物車仍然會說同樣的事情。
當我模擬按鈕點擊addToCart
方法時,怎么會這樣?
PASS src/__tests__/todo.test.js
● Console
console.log src/__tests__/todo.test.js:32 { price: 26 }
console.log src/__tests__/todo.test.js:33 [ { name: 'Green', cost: 4 }, { name: 'Red', cost: 8 }, { name: 'Blue', cost: 14 } ]
Enzyme的simulate
是在你的Todo組件上尋找一個onChange
事件,並沒有找到它。 你沒有將onChange
指定為prop,所以它沒有觸發它是有意義的。 如果這是您想要測試的方式,請將onChange
道具連接到您的組件。 來自文檔:
即使名稱暗示這模擬了一個實際的事件,.simulate()實際上會根據你給它的事件來定位組件的prop。 例如,.simulate('click')實際上會獲得onClick prop並調用它。
您正在嘗試使用類addtocart
模擬元素上的單擊。 但是,您沒有類addtocart
的元素。 您的添加按鈕的元素ID為submit
。
改變這個:
const submitButton = wrapper.find('.addtocart');
對此:
const submitButton = wrapper.find('#submit');
看完你的Todo
代碼后:
<input id="itemname" name="name" ref={this.nameRef} className="form-control" type="text" placeholder="Add item to List" />
和
<input name="cost" id="itemcost" ref={this.costRef} className="form-control" size="5" type="text" placeholder="Cost" />
我不認為wrapper.find('.cost')
會起作用。 我建議你做wrapper.find('#cost')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.