disconnectedLynx
disconnectedLynx

Reputation: 101

Can't find named elements with react-native-testing-library

I'm trying to get an element by its placeholder text but react-native-testing-library keeps throwing me the same errors:

expect(received).toEqual(expected) // deep equality

    Expected: "Cirurgião"
    Received: {"_fiber": {"_debugHookTypes": null, "_debugID": 451, "_debugIsCurrentlyTiming": 
false, "_debugNeedsRemount": false, "_debugOwner": [FiberNode], "_debugSource": [Object], 
"actualDuration": 0, "actualStartTime": -1, "alternate": null, "child": [FiberNode], 
"childExpirationTime": 0, "dependencies": null, "effectTag": 129, "elementType": [Function 
Component], "expirationTime": 0, "firstEffect": null, "index": 0, "key": null, "lastEffect":
 null, "memoizedProps": [Object], "memoizedState": null, "mode": 0, "nextEffect": null, 
"pendingProps": [Object], "ref": [Function ref], "return": [FiberNode], "selfBaseDuration": 0,
 "sibling": null, "stateNode": [Component], "tag": 1, "treeBaseDuration": 0, "type": [Function 
Component], "updateQueue": null}}


Here's the code i'm trying to test:

const { getByTestId, queryByTestId, getByPlaceholderText} = render(
      <Input placeholder="Cirurgião"
        testID='input_buscaCirurgiao_index'
        value={mockValue}
        autoCorrect={false}
        keyboardType={(Platform.OS === 'android') ? 'visible-password' : 'default'}
        onChangeText={mockState}
        onSubmitEditing={mockState}
        autoCapitalize='none' />
    );

    expect(getByPlaceholderText('Cirurgião')).toEqual('Cirurgião');

I've also tried to get the element I'm trying to test by getByTestId and queryByTestId and both had similar errors.

If I try testing with waitFor() =>, I don't get any error messages, even if I try changing the expected output like expect(getByTestId('test1').toEqual('test2');.

It runs smoothly, but it shouldn't.

I'm not sure what I'm doing wrong.

Upvotes: 0

Views: 1951

Answers (1)

hannojg
hannojg

Reputation: 1117

getByPlaceholderText returns you the first matching node. And actually, it succeeds in doing so. The node is represented as an object and your test says

    Expected: "Cirurgião"
    Received: {"_fiber": { //<- Here you actually received an object representing the node

This happens because you expect the object node to equal a string (string != node):

.toEqual('Cirurgião');

There are two possible cases you might want to test:

  1. Is the component actually there/is it being rendered?
  2. Does the view contain the placeholder I expect it to?

To test the first you would simply do:

getByPlaceholderText('Cirurgião')

it will throw if there was no component in the rendered tree, thus your test would fail.

Testing the second would be:

const input = getByPlaceholderText('Cirurgião');
expect(input.props.placeholder).toBe('Cirurgião');

Upvotes: 1

Related Questions