问题
I'm trying to write tests in jest for the examples shown in "Thinking in React" (http://facebook.github.io/react/docs/thinking-in-react.html)
And I am having a hard time using TestUtils.Simulate to provide a change-event to the search input object.
/** @jsx React.DOM */
jest.dontMock('../ProductTable.js');
jest.dontMock('../FilterableProductTable.js');
jest.dontMock('../SearchBar.js');
var React = require('react/addons');
var TestUtils = React.addons.TestUtils;
var FilterableProductTable = require('../FilterableProductTable.js');
var SearchBar = require('../SearchBar.js');
var PRODUCTS = [
{category: 'thing', name: 'glove', price: '$0.50', stocked: true},
{category: 'thing', name: 'spam', price: '$1.50', stocked: true},
{category: 'thing', name: 'glam', price: '$9.50', stocked: false},
{category: 'thing', name: 'blam', price: '$99.00', stocked: true},
{category: 'thing', name: 'sham', price: '$0.20', stocked: true},
];
describe('FilterableProductTable', function() {
it('creates the entire table', function () {
filterableProductTable = TestUtils.renderIntoDocument(
<FilterableProductTable
products={PRODUCTS}
filterText = {''}
inStockOnly = {false}
/>
);
var rows = TestUtils.scryRenderedDOMComponentsWithTag(filterableProductTable, 'tr');
expect(rows.length).toEqual(7); // 5 items and 2 headers
});
it('searches the table for proper stuff', function() {
filterableProductTable = TestUtils.renderIntoDocument(
<FilterableProductTable
products={PRODUCTS}
filterText = {''}
inStockOnly = {false}
/>
);
// var inputBox = document.querySelectorAll('#search-box');
// console.log(inputBox.innerHTML);
var inputObjects = TestUtils.scryRenderedDOMComponentsWithTag(filterableProductTable, 'input');
var inputBox = inputObjects[0];
// TestUtils.Simulate.keyUp(inputBox, {key: 'a'});
TestUtils.Simulate.change(inputBox, {target: {value: 'a'}});
var rows = TestUtils.scryRenderedDOMComponentsWithTag(filterableProductTable, 'tr');
expect(rows.length).toEqual(6); // FAILS. This is equal to 7 as in the previous test.
});
});
Does anyone have a suggestion? Am I using Testutils.Simulate incorrectly?
回答1:
I had the same problem recently and simply did this:
React.findDOMNode(inputBox).value = 'a';
TestUtils.Simulate.change(inputBox);
I could not make Simulate or SimulateNative to change the value so just changed the value on the node manually then triggered a change event via Simulate.
One of the developers of React mentioned on github that they are currently testing the Simulate.change the same way (setting value manually then triggering change). I don't know why they have it in the manuals still (if I read it correctly it was working in 0.11 but broken since 0.12).
来源:https://stackoverflow.com/questions/26762046/trouble-using-testutils-simulate-to-create-a-change-event-on-an-input-element