Playwright test failing: props return different values in Playwright testing UI and actual React app on Chrome browser

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

  • e2e (with Playwright)
  • blog-backend
  • blog-frontend

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: Matti Luukkainen')).toBeVisible(); // THIS DOES NOT WORK
      // await expect(page.getByRole('button', { name: 'remove' })).toBeVisible(); // THIS DOES NOT WORK
    });
  });
});

Below is the Playwright GUI output:

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: 665f9faa37d34c2da6c8f79e
}

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": "665f9faa37d34c2da6c8f79e"
    },
    "id": "665f9fab37d34c2da6c8f7a5"
}

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);

  // 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;

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật