Reputation: 103
I am trying to test a react component that has a properties that changes when the user logs in. I can't change the login prop from the testcafe suite itself because the user can only login clicking on a magic link that she receives on her email.
Given the example component below, how can I test the Logout button?
Test cafe will always see the isLoggedIn prop as false and it doesn't allow to set components props to some custom value while testing.
header.js
import React from 'react';
const Header = ({ isLoggedIn }) => (
<div>
{isLoggedIn ? (
<h1>text unreachable from testcafe</h1>
<button onClick={logout}>Logout</button>
) : (
<button onClick={login}>Login</button>
)}
</div>
);
export default Header;
test-cafe.js
import { ReactSelector } from 'testcafe-react-selectors';
import { waitForReact } from 'testcafe-react-selectors';
fixture`HEADER`
.page('http://localhost:3000')
.beforeEach(async () => {
await waitForReact();
});
test('Page should load the header', async (t) => {
const App = ReactSelector('App').withProps({ isLoggedIn: true });
const actual = App.find('h1').innerText;
const expected = 'text unreachable from testcafe';
await t.expect(actual).eql(expected);
});
Upvotes: 3
Views: 441
Reputation: 103
It turns out there isn't a proper way to do that.
At the moment there are two options:
1 - to short circuit the props you want to change using hidden buttons. I.e. you create a hidden button in dev mode and you click it in your tests to change props and hence the state of your application.
2 - I talked to the Magic Link support and they said they will add a feature in dev mode by the end of the year that will allow to sign in without having to click on an email link. You can enter the [email protected] email address and it will automatically sign in. That's handy!
Upvotes: 0
Reputation: 5227
The testcafe-react-selectors
module is not intended to change the react component state. To implement this scenario, you can mock the authorization via the 'magic link' or use tools for component testing like 'jest'.
Upvotes: 1
Reputation: 18592
I would change the design a little bit,
I would pass login
and logout
functions to the component as props so that it would be easy to test them
const Header = ({ isLoggedIn , login , logout }) => (
<div>
{isLoggedIn ? (
<button onClick={login}>Login</button>
) : (
<button onClick={logout}>Logout</button>
)}
</div>
);
for the testing
const logoutMock = jest.fn();
const component = mount(<Header ... logout={logoutMock} />);
const button = component.find('button').simulate('click');
expect(logoutMock).toBeCalled();
Upvotes: 1