Coder Social home page Coder Social logo

ci-examples's Introduction

06 Use context

In this example we will create a simple test over a custom hook that it will use the React Context API.

We will start from 05-component-unmount.

Steps

  • npm install to install previous sample packages:
npm install
  • Let's create languageContext:

./src/language.context.tsx

import * as React from 'react';

interface Context {
  language: string;
  setLanguage: (language: string) => void;
}

export const LanguageContext = React.createContext<Context>({
  language: '',
  setLanguage: () => {
    console.warn('Provider is not initialized');
  },
});

export const LanguageProvider: React.FunctionComponent = props => {
  const [language, setLanguage] = React.useState('es');

  return (
    <LanguageContext.Provider value={{ language, setLanguage }}>
      {props.children}
    </LanguageContext.Provider>
  );
};
  • If we want to use this context, we have to write something like this on top of our app:
<LanguageProvider>
....
</LanguageProvider>
  • And then use it like:

./src/language.hooks.ts

import * as React from 'react';
import { LanguageContext } from './language.context';

export const useLanguage = () => {
  const [message, setMessage] = React.useState('');
  const { language, setLanguage } = React.useContext(LanguageContext);

  React.useEffect(() => {
    setMessage(`The current language is: ${language}`);
  }, [language]);

  return {
    message,
    setLanguage,
  };
};
  • Let's add some specs:

./src/language.hooks.spec.ts

import { renderHook } from '@testing-library/react-hooks';
import { useLanguage } from './language.hooks';

describe('useLanguage specs', () => {
  it('', () => {
    // Arrange

    // Act

    // Assert

  });
});
  • should return a message with language equals "es" when it renders the hook:

./src/language.hooks.spec.ts

...
- it('', () => {
+ it('should return a message with language equals "es" when it renders the hook', () => {
    // Arrange

    // Act
+   const { result } = renderHook(() => useLanguage());

+   result.current.setLanguage('es');

    // Assert
+   expect(result.current.message).toEqual('The current language is: es');
  });
});
  • What is going on? That is because we have to initialize the Provider when we use a Context. IMPORTANT, rename to tsx:

./src/language.hooks.spec.tsx

+ import * as React from 'react';
import { renderHook } from '@testing-library/react-hooks';
+ import {LanguageProvider} from './language.context';
import { useLanguage } from './language.hooks';

describe('useLanguage specs', () => {
  it('should return a message with language equals "es" when it renders the hook', () => {
    // Arrange
+   const provider: React.FunctionComponent = props => (
+     <LanguageProvider>{props.children}</LanguageProvider>
+   );

    // Act
-   const { result } = renderHook(() => useLanguage());
+   const { result } = renderHook(() => useLanguage(), { wrapper: provider });

    result.current.setLanguage('es');

    // Assert
    expect(result.current.message).toEqual('The current language is: es');
  });
});
  • should return a message with language equals "english" when it call setLanguage with "english":

./src/language.hooks.spec.tsx

import * as React from 'react';
- import { renderHook } from '@testing-library/react-hooks';
+ import { renderHook, act } from '@testing-library/react-hooks';
import { LanguageProvider } from './language.context';
import { useLanguage } from './language.hooks';

...

+ it('should return a message with language equals "english" when it call setLanguage with "english"', () => {
+   // Arrange
+   const provider: React.FunctionComponent = props => (
+     <LanguageProvider>{props.children}</LanguageProvider>
+   );

+   // Act
+   const { result } = renderHook(() => useLanguage(), { wrapper: provider });

+   act(() => {
+     result.current.setLanguage('english');
+   });

+   // Assert
+   expect(result.current.message).toEqual('The current language is: english');
+ });

About Basefactor + Lemoncode

We are an innovating team of Javascript experts, passionate about turning your ideas into robust products.

Basefactor, consultancy by Lemoncode provides consultancy and coaching services.

Lemoncode provides training services.

For the LATAM/Spanish audience we are running an Online Front End Master degree, more info: http://lemoncode.net/master-frontend

ci-examples's People

Contributors

juanjopmelida avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.