Is it possible to run multiple tests in one browser window for playwright/test?
currently it will hit browser.close(); after every test even though they are testing on the same page which puts a lot of extra time on the tests.
test.beforeAll(async ({ browser }) => {
const context = await browser.newContext();
const page = await context.newPage();
await page.goto('https://example.com');
});
test('nav test', async ({ page }) => {
const name = await page.innerText('.navbar__title');
expect(name).toBe('Playwright');
});
test('header test', async ({ page }) => {
const name = await page.innerText('.navbar__header');
expect(name).toBe('Playwright');
});
When you create a tests like this test('header test', async ({page}) => { you're specifying page and telling it to create a new page context.
Remove the page from the test - and share the one you create from your .beforeAll
Try this:
test.describe('1 page multiple tests', () => {
let page;
test.beforeAll(async ({ browser }) => {
const context = await browser.newContext();
page = await context.newPage();
await page.goto('https://example.com');
});
test.afterAll(async ({ browser }) => {
browser.close;
});
test('nav test', async () => {
const name = await page.innerText('h1');
expect(name).toContain('Example');
});
test('header test', async () => {
const name = await page.innerText('h1');
expect(name).toContain('Domain');
});
});
Run it like this :
npx playwright test .\StackTests_SinglePage.spec.ts --headed
(you can see the name of my file in there)
You might need to toggle it down to 1 worker if it tries to parallel run your test.
For me, that code opens 1 borwser, 1 page, passes both tests the closes out.
Can you try wrapping the tests in a describe block? So they are treated as a group and not as an individual tests.
test.describe('two tests for same page', () => {
test('nav test', async ({ page }) => {
const name = await page.innerText('.navbar__title');
expect(name).toBe('Playwright');
});
test('header test', async ({ page }) => {
const name = await page.innerText('.navbar__header');
expect(name).toBe('Playwright');
});
});
Related
I'm trying to get the data from Node.js, but it is making like 5000 requests and the server is getting very slow and don't even load some of the other images in other pages. Do I need to limit the requests?
Any solutions?
const [data, SetData] = useState([]);
useEffect(() => {
axios.get(`/api/data/${id}`).then((response) => {
SetData(response.data)
})
})
When I'm adding }, []) to useEffect the images from Public folder are not showing.
Your effect probably missing the id as dependency.
Change it to be like that:
const [data, setData] = useState([]);
useEffect(() => {
if (id) {
axios.get(`/api/data/${id}`).then((response) => {
setData(response.data)
});
}
}, [id]);
useEffect runs after every render without the dependencies array, causing infinite loop
useEffect(() => {
axios.get(`/api/data/${id}`).then((response) => {
SetData(response.data)
});
//Infinite loop
});
Provide an empty dependencies array, this will cause the effect function to only run once after the component has rendered the first time.
useEffect(() => {
axios.get(`/api/data/${id}`).then((response) => {
SetData(response.data)
});
// Correct! Runs once after render with empty array
}, []);
I have a mock where it sets up a return value before all my tests. But I was wondering if you could update a value in the test itself. As you can see I want to just update the boolean value of mockedIsloading, without calling the entire mockedLoadStatus.mockReturnValue({...}) again in my test with a new isLoading value of true this time around.
Would be nice to just be able to call mockedIsloading.mockReturnValueOnce(true) but this does not seem to work.
import {
loadStatus,
} from 'pathToMyFile'
jest.mock('pathToMyFile')
const mockedLoadStatus jest.mocked(loadStatus)
const mockedMutate = jest.fn()
const mockedIsLoading = jest.fn().mockReturnValue(false)
beforeAll(() => {
mockedLoadStatus.mockReturnValue({
mutate: mockedMutate,
isLoading: mockedIsloading,
})
})
test('my test', () => {
mockedIsloading.mockReturnValueOnce(true)
render(<Wrapper />)
})
What do you mean "doesn't work"? I mean this works OK:
const mockedLoadStatus = jest.fn();
const mockedMutate = jest.fn()
const mockedIsLoading = jest.fn().mockReturnValue(false)
beforeAll(() => {
mockedLoadStatus.mockReturnValue({
mutate: mockedMutate,
isLoading: mockedIsLoading,
})
})
test('some test', () => {
expect(mockedLoadStatus().isLoading()).toBeFalsy();
})
test('my test', () => {
mockedIsLoading.mockReturnValueOnce(true)
expect(mockedLoadStatus().isLoading()).toBeTruthy();
expect(mockedLoadStatus().isLoading()).toBeFalsy();
})
Or am I missing something :) ?
I have a VPS running amazon linux with Node JS. I'm trying to run a node js script that sends a GET request to an API to get data, then sends a POST request to another API with said data. The script works when running using node in the terminal, but not after adding it to sudo crontab -e.
Now I know about the complications with absolute paths when using crontab, I've read many of the stackoverflow questions and I'm fairly certain pathing isn't the issue. To test this, I created a test script that creates a file in the root directory, and it works in crontab. This test script is in the SAME directory as the main script, which has me very confused.
The script uses two packages, Axios and Puppeteer. Here is the script with some information replaced with placeholders:
import axios from "axios";
import puppeteer from "puppeteer";
const apiKey = process.env.API_KEY
const USER_ID = process.env.USER_ID
const sitekey = process.env.SITE_KEY
const surl= 'url'
const url= 'url'
async function webSubmit (data) {
const browser = await puppeteer.launch({ headless: true, args: ['--no-sandbox'] });
const page = await browser.newPage();
await page.goto(url);
await page.$eval("input[name='data']", (el, data) => el.value = data, data)
await page.click('#submitButton')
setTimeout(() => {
browser.close()
}, 5000)
}
function checkStatus (id) {
axios.get(url)
.then(response => {
if (response.data === 'NOT_READY') {
setTimeout(() => {
checkStatus(id)
}, 10000)
} else {
const data = response.data.slice(3)
webSubmit(data)
}
})
.catch(e => console.log(e))
}
function post() {
const postUrl = url
axios.post(postUrl)
.then(response => {
const id = response.data.slice(3)
setTimeout(() => {
checkStatus(id)
}, 30000)
})
.catch(error => console.log(error))
}
post()
Test Script:
import * as fs from 'fs'
fs.writeFile("/vote" + Math.random(), "Hi", function(err) {
if(err){
return console.log(err)
}
console.log("File saved")
})
Crontab Jobs:
* * * * * /opt/bitnami/node/bin/node /home/bitnami/app/index.js
* * * * * cd /home/bitnami/app && /opt/bitnami/node/bin/node index.js
Both these jobs work if I change the index.js script to test.js, but not as index.js.
Any help would be appreciated, thank you!
I'm testing a functional component, that use React-Hooks and Redux-Saga. I can pass parameters in URL for the component, because they are a login page component.
My URL i pass is 'localhost/access/parameter', and when this parameter exists, i need to call a async redux saga, and if the fetch is OK, i put the result in redux-store. When the result is on redux-store, i have a useEffect that verify the result and if is OK, i put her in a input.
I can mock the result with axios, but i'm migrating to use only fetch. i mock the fetch, but when i use
mount(component), provided by enzyme, i do not how to await the redux-saga termine the request and useEffect do your job. I put a console log inside a effect, saga and log the input props to see your value prop, but the value is always empty . I tried to use setImmediate() and process.nextTick().
Links i use to write the code: 1,2, 3
I'm using formik, so they pass some props to me.
My component
const Login = ({
setFieldError, errors, response, fetchDomain, location, values, handleChange, handleBlur, setFieldValue, history,
}) => {
useEffect(() => {
async function fetchUrlDomain() {
const { pathname } = location;
const [, , domain] = pathname.split('/');
if (typeof domain !== 'undefined') {
await fetchDomain(domain);
}
}
fetchUrlDomain();
}, [fetchDomain, location]);
useEffect(() => {
if (typeof response === 'string') {
setFieldError('domain', 'Domain not found');
inputDomain.current.focus();
} else if (Object.keys(response).length > 0) {
setFieldValue('domain', response.Domain);
setFieldError('domain', '');
}
}, [response, setFieldValue, setFieldError]);
return (
<input name="domain" id="domain" value={values.domain} onChange={handleChange} onBlur={handleBlur} type="text" />
);
}
const LoginFormik = withFormik({
mapPropsToValues: () => ({ domain: '' }),
enableReinitialize: false,
validateOnBlur: false,
validateOnChange: false,
})(Login);
const mapStateToProps = () => ({ });
const mapDispatchToProps = dispatch => ({
fetchDomain: (value) => {
dispatch(action({}, constants.RESET_RESPONSE_DOMAIN));
dispatch(action(value, constants.FETCH_DOMAIN_REQUEST));
},
});
export default connect(mapStateToProps, mapDispatchToProps)(LoginFormik);
My Saga
export function* fetchDomain(action) {
const url = yield `${mainUrl}/${action.payload}`;
try {
const response = yield fetch(url).then(res => res.json());
yield put(reduxAction(response , constants.FETCH_DOMAIN_SUCCESS));
} catch (e) {
yield put(reduxAction(e, constants.FETCH_DOMAIN_FAILURE));
}
}
My Reducer
case constants.FETCH_DOMAIN_FAILURE:
return { ...initialState, response: 'Domain not found' };
case constants.FETCH_DOMAIN_SUCCESS: {
const { payload } = action;
return {
...initialState,
id: payload.Id,
apis: payload.Apis,
response: payload,
};
}
case constants.RESET_RESPONSE_DOMAIN:
return { ...initialState };
My Test
it('input with fetch only', (done) => {
const mockSuccessResponse = {
Id: 'fafafafa',
Apis: [],
Domain: 'NAME',
};
const mockJsonPromise = Promise.resolve(mockSuccessResponse);
const mockFetchPromise = Promise.resolve({
json: () => mockJsonPromise,
});
global.fetch = jest.fn().mockImplementation(() => mockFetchPromise);
const wrapper = mount(
<Provider store={store}>
<LoginForm
history={{ push: jest.fn() }}
location={{ pathname: 'localhost/login/Domain' }}
/>
</Provider>,
);
process.nextTick(() => {
const input = wrapper.find('#domain');
console.log(input.props());
expect(input.props().value.toLowerCase()).toBe('name');
global.fetch.mockClear();
done();
});
});
I expect my input have value, but he don't. I tried to use jest-fetch-mock but just don't work, and i want to use native jest methods, no thirty party libraries.
I cannot say what's wrong with your current code. But want to propose different approach instead.
Currently you are testing both redux part and component's one. It contradicts with unit testing strategy when ideally you should mock everything except module under the test.
So I mean if you focus on testing component itself it'd be way easier(less mocks to create) and more readable. For that you need additionally export unwrapped component(Login in your case). Then you can test only its props-vs-render result:
it('calls fetchDomain() with domain part of location', () => {
const fetchDomain = jest.fn();
const location = { pathName: 'example.com/path/sub' }
shallow(<Login fetchDomain={fetchDomain} location={location} />);
expect(fetchDomain).toHaveBeenCalledTimes(1);
expect(fetchDomain).toHaveBeenCalledWith('example.com');
});
it('re-calls fetchDomain() on each change of location prop', () => {
const fetchDomain = jest.fn();
const location = { pathName: 'example.com/path/sub' }
const wrapper = shallow(<Login fetchDomain={fetchDomain} location={location} />);
fetchDomain.mockClear();
wrapper.setProps({ location: { pathName: 'another.org/path' } });
expect(fetchDomain).toHaveBeenCalledTimes(1);
expect(fetchDomain).toHaveBeenCalledWith('another.org');
});
And the same for other cases. See with this approach if you replace redux with direct call to fetch() or whatever, or if you refactor that data to come from parent instead of reading from redux store you will not need to rewrite tests removing mocks to redux. Sure, you will still need to test redux part but it also can be done in isolation.
PS and there is no profit to await fetchDomain(...) in useEffect since you don't use what it returns. await does not work like a pause and that code may rather confuse reader.
I'm currently building a league of legends (a MOBA or multiplayer online battle arena game) search-based web app that essentially allows the user to search for their summoner's name and obtain general information regarding their search input. (The data is provided by the game's own third-party api)
I've been able to successfully retrieve the form data and perform the intended backend processes, however, upon the client's initial render, my results-listing component is already trying to fetch the nonexistent processed data.
How do I prevent the server request from firing until the server has actually successfully served the data?
(abridged single-component client example)
the summoner data endpoint is set to http://localhost:3001/api/summoner
server does not contain any additional routes
const App = () => {
const [summName, setSummName] = useState('');
const summonerFormData = new FormData();
// let data;
const findSummoner = () => {
summonerFormData.set('summonerName', summName);
}
// problem here
const data = axios.get('http://localhost:3001/api/summoner');
// axios.get('http://localhost:3001/api/summoner')
// .then(res => {
// data = res;
// });
return (
<div>
<form
method="POST"
action="http://localhost:3001/api/summoner"
onSubmit={findSummoner}
>
<input
value={summName}
name="summName"
onChange={e => setSummName(e.target.value)}
/>
<button type="submit">submit</button>
</form>
{data !== undefined &&
<div className="results">
data.map(match => {
<div>
<p>{match.kills}</p>
<p>{match.deaths}</p>
<p>{match.assists}</p>
</div>
})
</div>
}
</div>
)
}
Here's the Repo for some more context, but please don't hesitate to ask if you need more information or have any questions at all!
I really appreciate any help I can get!
Thanks!
Edits:
I've also tried using the useEffect hook considering the lifecycle point I'm trying to fetch would be componentDidMount, but wasn't quite sure what the solution was. Doing more research atm!
Close, but no cigar. Request gets stuck at 'pending'.
let data;
const fetchData = () => {
axios.get('http://localhost:3001/api/summoner');
};
useEffect(() => {
if (summName !== '') {
fetchData();
}
}, summName);
I tried putting the axios request within an async function and awaiting on the request to respond, and it seems to be working, however, the server is still receiving undefined when the client starts, which then is attempting to be fetched, never allowing the promise to be fulfilled.
const fetchData = async () => {
await axios
.get('http://localhost:3001/api/summoner')
.then(res => {
data = res;
})
.catch(() => {
console.log('error');
});
};
useEffect(() => {
fetchData();
}, [])
So I took the advice and recommendations from #imjared and #HS and I'm literally so close..
I just have one more problem... My data-mapping component is trying to map non-existent data before actually receiving it, giving me an error that it's unable to map match of undefined..
const [modalStatus, setModalStatus] = useState(false);
const [loading, setLoading] = useState(false);
const [data, setData] = useState({ hits: [] });
const [summName, setSummName] = useState('');
const [summQuery, setSummQuery] = useState('');
const summonerFormData = new FormData();
const prepareResults = async () => {
await setSummQuery(summName);
};
const findSummoner = async () => {
setLoading(true);
setModalStatus(false);
await summonerFormData.set('summonerName', summQuery);
};
useEffect(() => {
const fetchData = async () => {
if (summQuery) {
setData({ hits: [] });
console.log('fetching');
await axios
.get('http://localhost:3001/api/summoner')
.then(res => {
setData(res.data);
setLoading(false);
setModalStatus(true);
return data;
})
.catch(error => {
console.log(error);
});
}
};
fetchData();
}, [summQuery]);
SUCCESS! Thank you guys! Here's what ended up working for me:
const findSummoner = async () => {
setSummQuery(summName);
};
useEffect(() => {
setData({ hits: [] });
summonerFormData.set('summonerName', summQuery);
const fetchData = async () => {
setModalStatus(false);
setLoading(true);
if (summQuery !== '') {
setLoading(true);
console.log('fetching');
await axios
.get('/api/summoner')
.then(res => {
setData({
hits: res.data,
});
setError(false);
setLoading(false);
setModalStatus(true);
return data;
})
.catch(() => {
setError(true);
console.log('error');
});
}
};
if (summQuery !== '') {
fetchData();
}
}, [summQuery]);
This flow will help you design better -
1. User - input
2. Hit - search
3. Set loading in state - true,
5. Set data in state - empty
6. Call api
7. Get data
8. Then, set data in state
6. Set loading in state - false
Along the side in the render/return -
1. if loading in the state - indicate loading.
2. if loading done( false ) and data is not empty - show data.
3. if loading done and data is empty - indicate 'not-found'.
Coming to the initial render part - the axios.get() calls the api, which should only be initiated once the form is submitted in the case. Therefore, that logic should be moved inside the event-handler.