DEV Community

ynwd
ynwd

Posted on

UseEffect React Testing

This is a modification of the App.tsx and App.test.tsx CRAs. It uses useEffect to get the text from the Golang API.

.
├── cloudbuild.yaml
├── cmd
│   ├── build
│   │   ├── index.gohtml
│   │   └── main.go
│   └── main.go
├── firebase.json
├── go.mod
├── internal
│   ├── app.go
│   └── app_test.go
├── package.json
├── serverless.go
└── web
    └── home
        ├── craco.config.js
        ├── package.json
        ├── public
        ├── src
        │   ├── App.css
        │   ├── App.test.tsx
        │   ├── App.tsx
        │   ├── index.css
        │   ├── index.tsx
        │   ├── logo.svg
        │   ├── react-app-env.d.ts
        │   ├── reportWebVitals.ts
        │   └── setupTests.ts
        ├── tailwind.config.js
        └── tsconfig.json
Enter fullscreen mode Exit fullscreen mode

Backend

Golang API

package internal

import (
    "context"

    "github.com/fastrodev/fastrex"
)

func Handler(req fastrex.Request, res fastrex.Response) {
    res.Send("The best interface is no interface")
}

func CreateApp() fastrex.App {
    ctx := context.Background()
    app := fastrex.New()
    app.Ctx(ctx)
    app.Get("/api", Handler)
    return app
}


Enter fullscreen mode Exit fullscreen mode

Entry point

package serverless

import (
    "net/http"

    "github.com/ynwd/mnrp/internal"
)

func Main(w http.ResponseWriter, r *http.Request) {
    internal.CreateApp().Serverless(true).ServeHTTP(w, r)
}

Enter fullscreen mode Exit fullscreen mode

Frontend

App.tsx

import React, { useEffect, useState } from 'react';
import logo from './logo.svg';
import './App.css';

function App() {
  const [value, setValue] = useState("");
  useEffect(() => {
    async function getText() {
      let response = await fetch('/api')
      const d = await response.text()
      setValue(d)
    }
    getText()
  }, [value]);

  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <h3>
          {value}
        </h3>
      </header>
    </div>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

App.test.tsx

import React from 'react';
import { rest } from 'msw';
import { setupServer } from 'msw/node';
import { render, screen } from '@testing-library/react';
import App from './App';

const server = setupServer(
  rest.get('/api', async (req, res, ctx) => {
    return res(ctx.text("The best interface is no interface"));
  })
);

beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

test('loads and displays greeting', async () => {
  render(<App />);
  const linkElement = await screen.findByText('The best interface is no interface');
  screen.debug()
  expect(linkElement).toBeInTheDocument();
});
Enter fullscreen mode Exit fullscreen mode

Top comments (0)