I am creating an e2e testing for my application using Playwright (version 1.44.1). I have a react 18 application (created with Vite) for a blogs app. When I run the application the UI shows correct props in the React components as well as console logs. However, when I run my Playwright tests in the Playwright GUI the props show different values and so the tests fail. I do not know how this is happening. Any help would be appreciated. Below are my files.
I have 3 folders
QUESTION: I do not understand why the props are different on the Chrome browser when run normally and the props are different in the Playwright tests. The props shape should have been the same. What am I doing wrong here?
My test file blog_app.spec.js
in the e2e
folder: Please note that I have written other tests and all others pass.
const { test, expect, beforeEach, describe } = require('@playwright/test');
const { loginWith, createBlog } = require('./helper');
describe('Blog app', () => {
beforeEach(async ({ page, request }) => {
// empty the database
await request.post('http:localhost:3003/api/testing/reset');
// create a user for the backend
await request.post('http://localhost:3003/api/users', {
data: {
name: 'First Last',
username: 'first',
password: 'last'
}
});
await page.goto('http://localhost:5173');
});
test('front page can be opened', async ({ page }) => { });
test('Login form is shown', async ({ page }) => { });
describe('Login', () => {
test('succeeds with correct credentials', async ({ page }) => { });
test('fails with wrong credentials', async ({ page }) => { });
});
describe('When logged in', () => {
beforeEach(async ({ page }) => {
await loginWith(page, 'first', 'last');
});
// THIS TEST DOES NOT WORK AS EXPECTED
test('a new blog can be created', async ({ page }) => {
await createBlog(page, 'first blog title', 'first blog author', 'first blog url');
await expect(page.locator('li').filter({ hasText: 'first blog title' })).toBeVisible();
await page.getByText('first blog title').locator('..').getByRole('button', { name: 'view' }).click();
await expect(page.getByText('Author: first blog author')).toBeVisible();
await expect(page.getByText('Likes: 0')).toBeVisible();
await expect(page.getByText('URL: first blog url')).toBeVisible();
await expect(page.getByText('Added by: ')).toBeVisible(); // THIS WORKS
await expect(page.getByText('Added by: First Last')).toBeVisible(); // THIS DOES NOT WORK
// await expect(page.getByRole('button', { name: 'remove' })).toBeVisible(); // THIS DOES NOT WORK
});
});
});
Below is the Playwright GUI output:
NOTE: the name, username, and logged in username are undefined in the Playwright GUI.
If you notice in the Playwright GUI console, the props received by the Blog.jsx
file the object shape is how it is saved to the database in the backend:
{
title: first blog title,
author: first blog author,
url: first blog url,
likes: 0,
user: 665fac3a37d34c2da6c8f899
}
Now running this application in a chrome browser receives different props shape:
Chrome browser view: Please notice the user that creates the blog name appears in the blog info. This shape is correct here.
The props shape in the Chrome browser is: In the frontend the below props show up correctly, and are also correctly reflected in the UI.
{
"title": "first blog title",
"author": "first blog author",
"url": "first blog url",
"likes": 0,
"user": {
"username": "first",
"name": "First Last",
"id": "665fac3a37d34c2da6c8f899"
},
"id": "665fac3b37d34c2da6c8f8a0"
}
See React Components props from the Chrome browser:
App.jsx
file in the frontend:
import { useEffect, useRef, useState } from 'react';
import Blog from './components/Blog';
import LoginForm from './components/LoginForm';
import NewBlogForm from './components/NewBlogForm';
import Notification from './components/Notification';
import Togglable from './components/Togglable';
import blogService from './services/blogs';
import loginService from './services/login';
const compareBlogs = (a, b) => {
if (a.likes < b.likes) return 1;
if (a.likes > b.likes) return -1;
return 0;
};
const sortBlogsAsPerMostLikedFirst = (blogs) => {
const sortedBlogs = blogs.sort(compareBlogs);
return sortedBlogs;
};
const App = () => {
const [blogs, setBlogs] = useState([]);
const blogFormRef = useRef();
const [notification, setNotification] = useState({
message: '',
isError: false,
});
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [user, setUser] = useState(null);
useEffect(() => {
blogService.getAll().then((initialBlogs) => {
const sortedBlogs = sortBlogsAsPerMostLikedFirst(initialBlogs);
setBlogs(sortedBlogs);
});
}, []);
useEffect(() => {
const loggedUserJSON = window.localStorage.getItem('loggedBlogappUser');
if (loggedUserJSON) {
const user = JSON.parse(loggedUserJSON);
setUser(user);
blogService.setToken(user.token);
}
}, []);
const removeNotificationAfterFiveSeconds = () => {
setTimeout(() => {
setNotification({
message: '',
isError: false,
});
}, 5000);
};
const handleLogin = async (event) => {
event.preventDefault();
try {
const user = await loginService.login({
username,
password,
});
window.localStorage.setItem('loggedBlogappUser', JSON.stringify(user));
blogService.setToken(user.token);
setUser(user);
} catch (error) {
setNotification({
message: error.response.data.error,
isError: true,
});
removeNotificationAfterFiveSeconds();
}
};
const handleLogout = async () => {
try {
window.localStorage.removeItem('loggedBlogappUser');
setUser(null);
setUsername('');
setPassword('');
} catch (exception) {
console.error(exception.message);
}
};
const addBlog = (blogObject) => {
blogFormRef.current.toggleVisibility();
blogService
.create(blogObject)
.then((returnedBlog) => {
setBlogs(blogs.concat(returnedBlog));
setNotification({
message: `SUCCESS: Added ${returnedBlog.title} blog`,
isError: false,
});
removeNotificationAfterFiveSeconds();
})
.catch((error) => {
setNotification({
message: error.response.data.error,
isError: true,
});
removeNotificationAfterFiveSeconds();
});
};
const increaseLikes = (blogToUpdate) => {
const blog = blogs.find((b) => b.id === blogToUpdate.id);
const updatedBlog = { ...blog, likes: blog.likes + 1 };
blogService
.update(blog.id, updatedBlog)
.then((returnedBlog) => {
const blogList = blogs.map((blog) => blog.id !== blogToUpdate.id ? blog : returnedBlog);
const sortedBlogs = sortBlogsAsPerMostLikedFirst(blogList);
setBlogs(sortedBlogs);
})
.catch((error) => {
setNotification({
message: `Blog '${blog.title}' was already removed from server`,
isError: true,
});
removeNotificationAfterFiveSeconds();
const blogList = blogs.filter((b) => b.id !== blogToUpdate.id);
setBlogs(blogList);
console.error(error.message);
});
};
const deleteBlog = (blog) => {
const toDelete = window.confirm(`Delete "${blog.title}" blog?`);
console.log({ toDelete });
if (toDelete) {
blogService
.deleteBlog(blog)
.then(() => {
const blogList = blogs.filter((b) => blog.id !== b.id);
setBlogs(blogList);
console.log('Blog deleted');
})
.catch((err) => {
console.log(err.message);
alert('Sorry! Blog cannot be deleted as it is not created by you.');
});
}
};
const loginForm = () => {
return (
<Togglable buttonLabel="login">
<LoginForm
username={username}
password={password}
handleUsernameChange={({ target }) => setUsername(target.value)}
handlePasswordChange={({ target }) => setPassword(target.value)}
handleSubmit={handleLogin}
/>
</Togglable>
);
};
const blogForm = () => (
<Togglable buttonLabel="new blog" ref={blogFormRef}>
<NewBlogForm createBlog={addBlog} />
</Togglable>
);
console.log('App.jsx', JSON.stringify(blogs)); // DEBUG
return (
<div>
<h1>Blogs</h1>
<Notification notification={notification} />
{!user && loginForm()}
{user && (
<div>
<p>
{user.name} logged in{' '}
<button type="button" onClick={handleLogout}>
logout
</button>
</p>
{blogForm()}
<ul style={{ listStyleType: 'none', padding: 0 }}>
{blogs.map((blog) => (
<Blog
key={blog.id}
blog={blog}
loggedInUsername={user.username}
handleLikes={() => increaseLikes(blog)}
handleDeleteBlog={() => deleteBlog(blog)}
/>
))}
</ul>
</div>
)}
</div>
);
};
export default App;
The Blog.jsx
file in the frontend:
import { useState } from 'react';
const Blog = ({ blog, loggedInUsername, handleLikes, handleDeleteBlog }) => {
console.log('Blog.jsx', blog); // DEBUG
console.log('Blog creator username: ', blog.user.username); // DEBUG
console.log('Blog creator name: ', blog.user.name); // DEBUG
console.log('Logged in username: ', loggedInUsername, ); // DEBUG
// styles
const blogStyle = {
paddingLeft: 10,
paddingRight: 10,
paddingBottom: 10,
border: 'solid',
borderWidth: 1,
marginBottom: 5,
};
const removeBtnStyle = {
backgroundColor: 'lightblue',
padding: 5,
borderRadius: 10,
fontWeight: 'bold',
};
const [viewBlogInfo, setViewBlogInfo] = useState(false);
const toggleShow = () => {
setViewBlogInfo(!viewBlogInfo);
};
return (
<li style={blogStyle} className='blog'>
<p>
<span>{blog.title}{' '}</span>
<button onClick={toggleShow} className='viewHideBtn'>
{viewBlogInfo ? 'hide' : 'view'}
</button>
</p>
{viewBlogInfo && (
<div>
<div>
<div>Author: {blog.author}</div>
<div>
<span data-testid='likes'>Likes: {blog.likes}</span>
<button onClick={handleLikes} className='likeBtn'>like</button>
</div>
<div>URL: {blog.url}</div>
<div>Added by: {blog.user.name}</div>
</div>
<br />
{blog.user.username === loggedInUsername && (
<div>
<button style={removeBtnStyle} onClick={handleDeleteBlog} className='removeBtn'>
remove
</button>
</div>
)}
</div>
)}
</li>
);
};
export default Blog;
The blogs.js
file for controllers in the backend:
const blogsRouter = require('express').Router();
const Blog = require('../models/blog');
const middleware = require('../utils/middleware');
blogsRouter.get('/', async (request, response) => {
const blogs = await Blog.find({}).populate('user', { username: 1, name: 1 });
response.json(blogs);
});
blogsRouter.get('/:id', async (request, response) => {
const blog = await Blog.findById(request.params.id).populate('user', { username: 1, name: 1 });
if (blog) {
response.json(blog);
} else {
response.status(404).end();
}
});
blogsRouter.post('/', middleware.userExtractor, async (request, response) => {
const user = request.user;
const body = request.body;
const blog = new Blog({
title: body.title,
author: body.author,
url: body.url,
likes: body.likes || 0,
user: user._id,
});
const savedBlog = await blog.save();
user.blogs = user.blogs.concat(savedBlog.id);
await user.save();
response.status(201).json(savedBlog);
});
blogsRouter.put('/:id', async (request, response, next) => { });
blogsRouter.delete('/:id', middleware.userExtractor, async (request, response) => { });
module.exports = blogsRouter;
I figured out the answer. I fixed my POST request in the blogs.js
backend controller.
blogsRouter.post('/', middleware.userExtractor, async (request, response) => {
const user = request.user;
const body = request.body;
const blog = new Blog({
title: body.title,
author: body.author,
url: body.url,
likes: body.likes || 0,
user: user._id,
});
const savedBlog = await blog.save();
user.blogs = user.blogs.concat(savedBlog._id);
await user.save();
// convert the user id string field to user object with:
// user: {id: "", username: "", name: "W"}
const blogReturned = await savedBlog.populate('user', { username: 1, name: 1 });
response.status(201).json(blogReturned);
});
After I save the object in the original object shape. I change the shape when returning the values to the UI by adding the username and name fields when populating the object. I did it like this because I don't want to change the shape of how I am storing values in the database.
I don't know if this is an efficient way of achieving this.
Now my Playwright tests pass without any issues. Please see image below: