IT |
気になる、記になる… |
Twitter、Twitter APIに月額約70万円の「Pro」プランを追加 |
https://taisy0.com/2023/05/26/172203.html
|
enterp |
2023-05-26 07:56:18 |
IT |
気になる、記になる… |
YouTube、「ストーリー」を6月26日で廃止へ |
https://taisy0.com/2023/05/26/172201.html
|
youtube |
2023-05-26 07:50:49 |
IT |
気になる、記になる… |
LINEMO、「スマホプラン」に乗り換えで15,000円相当のPayPayポイントが貰えるキャンペーンを開始(6月5日まで) |
https://taisy0.com/2023/05/26/172198.html
|
linemo |
2023-05-26 07:45:49 |
IT |
ITmedia 総合記事一覧 |
[ITmedia News] カシオ「G-SHOCK」値上げ、6月1日から 100製品以上 |
https://www.itmedia.co.jp/news/articles/2305/26/news213.html
|
gshock |
2023-05-26 16:49:00 |
IT |
ITmedia 総合記事一覧 |
[ITmedia News] ARグラスのNreal、社名とブランドを「XREAL」へ変更 |
https://www.itmedia.co.jp/news/articles/2305/26/news212.html
|
itmedianewsar |
2023-05-26 16:47:00 |
IT |
ITmedia 総合記事一覧 |
[ITmedia PC USER] Nrealが社名/ブランド名を「XREAL」に変更 |
https://www.itmedia.co.jp/pcuser/articles/2305/26/news206.html
|
itmediapcusernreal |
2023-05-26 16:12:00 |
TECH |
Techable(テッカブル) |
表彰事業のDX化を支援。アワードプロセスを一元管理できるサービスが登場 |
https://techable.jp/archives/208561
|
excel |
2023-05-26 07:00:57 |
python |
Pythonタグが付けられた新着投稿 - Qiita |
Pydanticで自作の検証ルールを追加する |
https://qiita.com/NMZ0429/items/145b56cd0916519b1cf0
|
icimportbasemodelclasstim |
2023-05-26 16:53:13 |
python |
Pythonタグが付けられた新着投稿 - Qiita |
WEBアプリケーションにおけるセッション管理(1) |
https://qiita.com/Kosuke0906/items/45bdef6efae3797a2d2f
|
記事 |
2023-05-26 16:27:57 |
python |
Pythonタグが付けられた新着投稿 - Qiita |
Twitter API Client を開発する過程の忘備録 |
https://qiita.com/yan7010/items/27ada65b9b1c15d72457
|
twitterapiclient |
2023-05-26 16:11:58 |
海外TECH |
DEV Community |
Learn serverless on AWS step-by-step - Emails |
https://dev.to/kumo/learn-serverless-on-aws-step-by-step-emails-49hp
|
Learn serverless on AWS step by step Emails TL DRIn this series I try to explain the basics of serverless on AWS to enable you to build your own serverless applications With last article we discovered how to orchestrate AWS services using Step Functions In this article let s dive into SES a service that allows you to send emails from your application IntroductionIn this series I try to explain the basics of serverless on AWS to enable you to build your own serverless applications We already learned how to create Lambda functions interacting with databases file storage authentication and more Now is time to implement some side effects in your application Emails are a good first step they allow you to send receipts to your users or to send them a password reset link for example This article will be tackle two topics How to setup SES to send emails from your own domain name for a professional lookHow to send simple templated emails to your users from a Lambda functionHere is the final architecture of the application we will build This is a practical introduction if you want to dive deeper into the SES theory I recommend you to read and older article I wrote a few months ago that develops more advanced topics like reputation management DKIM attachments UI etc Send emails from your own domain nameIn this part you will create the setup to send emails from your own domain name It will make them look more professional and will help you to keep a good reputation Downside it requires you to own a domain name which is not free If you don t want to spend money I will tackle a free alternative in the next part Buy a domain nameIf you don t have a domain name yet you can buy one on AWS or on any other registrar I bought mine pchol fr on AWS and I will use it in this tutorial The only required part is to be able to manage the DNS records of your domain name Setup a hosted zone in Amazon RouteTo send emails from your own domain name you need to prove to AWS that you own it To do so you will need to create a hosted zone in Amazon Route It is a DNS service that allows you to manage your domain name You will plug it to the domain name you bought in the previous step Like in all previous articles you will use the AWS CDK If you need a refresher on how to setup a CDK project check the first article of this series To create the hosted zone the following code does the trick import as cdk from aws cdk lib import Construct from constructs import path from path const DOMAIN NAME pchol fr Replace with your own domain nameexport class LearnServerlessStack extends cdk Stack constructor scope Construct id string props cdk StackProps super scope id props const hostedZone new cdk aws route HostedZone this hostedZone zoneName DOMAIN NAME Let s run a first deployment it should provision a hosted zone in Route There is a manual step to execute here you need to validate the hosted zone with your domain name To do so head to the Route console and copy the DNS records that were created Then go to your domain name registrar and add these records to your domain name It should look like this With this step done you have successfully validated your hosted zone and it will allow you to send emails from your domain name later Setup SES to send emailsTime to setup SES we will provision two resources A SES identity that will give you authorization to send emails from AWS An email template that will allow you to send templated emails from your application Create a SES identity previous code inside the constructor const identity new cdk aws ses EmailIdentity this sesIdentity identity cdk aws ses Identity publicHostedZone hostedZone If you want to send emails for free use a real email address to create the SES identity const MY EMAIL ADDRESS john gmail com Replace it with a REAL email address you ownconst identity new cdk aws ses EmailIdentity this sesIdentity identity cdk aws ses Identity email MY EMAIL ADDRESS The code is pretty straightforward you create a SES identity and you pass it the hosted zone you created in the previous step It will automatically create DNS CNAME records in your hosted zone proving to AWS that you own your domain name and allowing you to send emails from it If you skipped the first part and don t own a domain name use the commented code to create the identity It will allow you to send emails for free but they will be sent from a real email address and not from your domain name You will have to verify the email address by clicking on a link sent by AWS during the next deployment Create a SES templateSES templates allow you to send emails that contain HTML and CSS First step create a template file in your project that will contain the HTML and CSS of your email I created a simple template that looks like this export const emailHtmlTemplate lt html gt lt head gt lt style gt font family sans serif text align center padding margin title color fff background bb padding em container border px solid bb border radius em margin em auto max width px overflow hidden message padding em line height em color c footer font size em color lt style gt lt head gt lt body gt lt div class container gt lt div class title gt lt h gt Hello username lt h gt lt div gt lt div class message gt lt p gt message lt p gt lt div gt lt div gt lt p class footer gt This is an automated message please do not try to answer lt p gt lt body gt lt html gt It contains two placeholders username and message that will be replaced by the values you pass to the template Placeholders have to follow this syntax and you can use as many as you want Be careful when using CSS some properties like flex ️ are not supported by all email clients You can check this website to see which properties are supported by which email clients Another solution is to use a CSS framework that will do the hard compatibility work for you I use MJML in my in depth article about SES I explain how to use it to create responsive emails Final step provision the SES template using the CDK import emailHtmlTemplate from emailHtmlTemplate previous code inside the constructor const emailTemplate new cdk aws ses CfnTemplate this emailTemplate template htmlPart emailHtmlTemplate subjectPart Hello username Pretty straightforward the only new part is the subjectPart It contains the subject of the email and it can also contain placeholders Send emails from a Lambda functionYou are ready to send your first email To do so we will create a lambda function that will send the email It will be triggered by an API Gateway endpoint and it will receive the username message and email address of the recipient as body It will then send an email to the recipient using the template we created earlier First let s create the provisioning code for the lambda function previous code inside the constructor const sendEmail new cdk aws lambda nodejs NodejsFunction this sendEmail entry path join dirname sendEmail handler ts handler handler environment SENDER EMAIL contact identity emailIdentityName you can use what you want before the SENDER EMAIL MY EMAIL ADDRESS Use this line if you don t own a domain name TEMPLATE NAME emailTemplate ref sendEmail addToRolePolicy new cdk aws iam PolicyStatement actions ses SendTemplatedEmail resources const myFirstApi new cdk aws apigateway RestApi this myFirstApi const sendEmailResource myFirstApi root addResource send email sendEmailResource addMethod POST new cdk aws apigateway LambdaIntegration sendEmail This code does things It creates a lambda function with environment variables SENDER EMAIL and TEMPLATE NAME The first one contains the email address of the sender and the second one contains the name of the template we created earlier It grants the lambda function the permission to send emails using the ses SendTemplatedEmail action The target resource is which means that the lambda function can send emails to any email address It creates a POST API Gateway endpoint that will trigger the lambda function when called Finaly let s create the code of the lambda function import SESvClient SendEmailCommand from aws sdk client sesv const sesClient new SESvClient export const handler async body body string gt const senderEmail process env SENDER EMAIL const templateName process env TEMPLATE NAME if senderEmail templateName throw new Error Missing environment variables const username email message JSON parse body as username string email string message string if username email message return statusCode body JSON stringify message Missing parameters const formattedMessage message replace n g lt br gt await sesClient send new SendEmailCommand FromEmailAddress senderEmail Content Template TemplateName templateName TemplateData JSON stringify username message formattedMessage Destination ToAddresses email return statusCode body JSON stringify message Email sent This code does things It parses the environment variables set in the last code snippet and the body of the request It formats the message to replace n by lt br gt so that the message is displayed correctly in the email s HTML I sends an email using the AWS SDK It uses the SendEmailCommand This command takes parameters FromEmailAddress the email address of the sender It has to be verified in SES which is why we created the identity earlier Content the content of the email It contains the name of the template and the data to replace the placeholders ️The data has to contain exactly the same keys as the placeholders in the templateDestination the email addresses of the recipient Deploy the stack and you are ready to send your first email npm run cdk deploy Testing timeOne last step sorry if you just created your first SES identity your AWS account is surely in the SES sandbox It is a protection mechanism to prevent people from sending spam It means that you can only send emails to verified email addresses To test your code you will need to verify your email address You can do it in the SES console by manually creating a new identity corresponding to the email address you want to send emails to Now you can test your code by sending a POST request to the API endpoint with the right body I used n separators to add new lines in the message Here is how it looks like in my mailbox ConclusionThis tutorial was a shallow introduction to SES It was only a first step if you plan to send professional looking emails while keeping your domain reputation high you will need to learn more about SES I recommend you a previous article I wrote about SES which was a deep dive into the service I plan to continue this series of articles on a bi monthly basis I already covered the creation of simple lambda functions and REST APIs as well as interacting with DynamoDB databases and S buckets You can follow this progress on my repository I will cover new topics like creating event driven applications type safety and more If you have any suggestions do not hesitate to contact me I would really appreciate if you could react and share this article with your friends and colleagues It will help me a lot to grow my audience Also don t forget to subscribe to be updated when the next article comes out I you want to stay in touch here is my twitter account I often post or re post interesting stuff about AWS and serverless feel free to follow me |
2023-05-26 07:51:51 |
海外TECH |
DEV Community |
Key Concepts in Coding |
https://dev.to/garrywilliams/key-concepts-in-coding-14lb
|
Key Concepts in CodingCoding encompasses a wide range of concepts and principles that are fundamental to understanding and practicing programming Here are some key concepts in coding Algorithms Algorithms are step by step procedures or sets of rules for solving problems or performing tasks They form the foundation of coding by outlining the logical and computational processes required to achieve a specific outcome Variables Variables are containers used to store and manipulate data within a program They can hold different types of values such as numbers text or boolean true false values Variables allow programmers to work with and manipulate data dynamically Data Types Data types define the kind of data that can be stored in a variable Common data types include integers whole numbers floating point numbers decimal numbers strings text booleans true false arrays collections of data and objects complex data structures Control Structures Control structures enable programmers to control the flow of execution in a program They include conditional statements e g if else switch for making decisions based on certain conditions and looping statements e g for while for executing a block of code repeatedly Functions Functions are reusable blocks of code that perform specific tasks They allow programmers to break down complex problems into smaller manageable pieces Functions take inputs parameters and produce outputs providing a way to encapsulate and organize code for better readability and maintainability Object Oriented Programming OOP OOP is a programming paradigm that organizes code around objects which are instances of classes Objects have properties attributes and behaviors methods associated with them OOP concepts include encapsulation inheritance and polymorphism which help in building modular reusable and extensible code Modularity Modularity refers to the practice of breaking down code into separate independent modules or functions This approach improves code organization readability and reusability as well as facilitates collaborative development Debugging Debugging is the process of finding and fixing errors or bugs in a program It involves identifying and understanding the cause of unexpected behavior and using tools and techniques to resolve issues and ensure the program functions as intended Version Control Version control systems such as Git enable programmers to track and manage changes to their codebase They provide mechanisms for collaboration allowing multiple developers to work on the same codebase simultaneously roll back to previous versions and merge changes Testing Testing involves systematically checking the behavior and correctness of code It helps identify and prevent defects or unexpected behavior Testing can be done through various techniques including unit testing testing individual components integration testing testing interactions between components and system testing testing the entire system These concepts provide a foundation for understanding and writing code regardless of the programming language or domain Mastery of these concepts enables developers to tackle a wide range of programming problems effectively |
2023-05-26 07:34:48 |
海外TECH |
DEV Community |
An Introduction to Key Services for Cloud Success |
https://dev.to/prasadkpd/an-introduction-to-key-services-for-cloud-success-2n3d
|
An Introduction to Key Services for Cloud SuccessBusinesses of all sizes are leveraging the power of cloud computing for innovation scalability and cost efficiency in today s digital landscape Amazon Web Services AWS is known as a leader among cloud service providers delivering a comprehensive portfolio of services that cater to a wide range of corporate demands In this article I will present an overview of AWS and explore its core services providing the foundation for your AWS adventure Understanding AWS Amazon Web Services AWS is a cloud computing platform offered by Amazon that allows businesses to design deploy and manage applications and infrastructure in the cloud Organizations can use AWS to access a flexible and scalable infrastructure allowing them to focus on their core skills rather than hardware and data centres Key Services in AWS Amazon EC Elastic Compute Cloud Amazon EC is a core AWS service that provides scalable computation capacity in the cloud It allows users to launch virtual servers called instances which may be easily built and customized to fit unique computing needs EC instances are available in a variety of configurations ranging from general purpose instances for everyday workloads to specialized instances for purposes like as machine learning or high performance computing Amazon S Simple Storage Service Amazon S is an object storage service that allows companies to store and retrieve massive volumes of data It offers a long lasting and secure storage solution that ensures data availability and durability across multiple regions S allows you to store and retrieve an unlimited quantity of data from anywhere on the internet making it excellent for backup data archiving content sharing and many other applications AWS Lambda AWS Lambda is a serverless computing solution that enables developers to run code without the need for server provisioning or management It allows you to concentrate on writing code and developing applications while AWS Lambda manages infrastructure and scalability automatically You only pay for the compute time used by your code when using Lambda making it a cost effective and efficient alternative for operating event driven apps and microservices Amazon RDS Relational Database Service Amazon RDS is a managed database service that makes it easier to set up run and scale relational databases in the cloud It provides high availability automatic backups and automated software patching for common database engines such as MySQL PostgreSQL Oracle and SQL Server RDS enables enterprises to offload the administrative responsibilities associated with database management allowing them to focus on application development Amazon CloudFront Amazon CloudFront is a content delivery network CDN service that speeds up web content delivery to end users It caches static and dynamic content at global edge locations to reduce latency and improve performance CloudFront connects easily with other AWS services making it simple to distribute content stream media and serve APIs with minimal latency and high data transfer speeds Conclusion Understanding the key services provided by AWS is critical as you begin your AWS journey This article presented an overview of Amazon Web Services AWS and emphasized essential services such as Amazon EC S AWS Lambda Amazon RDS and Amazon CloudFront These services serve as the foundation for developing scalable and robust cloud applications AWS provides a diverse ecosystem of services each designed for different business demands and technical requirements Exploring these services in greater depth will allow you to fully utilize AWS and reap the benefits of cloud computing In the following articles in this day AWS series we ll delve deeper into each of these services investigating their capabilities use cases and best practices Stay tuned as we explore the many possibilities that AWS provides and assist you toward being a skilled cloud user |
2023-05-26 07:32:56 |
海外TECH |
DEV Community |
10x Query Performance with a Database Index |
https://dev.to/dbvismarketing/10x-query-performance-with-a-database-index-5406
|
x Query Performance with a Database IndexFor ages indexes have been the cornerstone of database performance Indexes are one of the main measures to speed up reading SELECT operations and in this blog we re telling you all about them Have a read Ever since open source databases have been a thing indexes have been that something that improves their performance In different database management systems different indexes have different usage types some work together with certain types of indexes some cover queries only partly but all of them one thing in common they speed up SELECT operations Types of Database IndexesAs you may know database indexes have a couple of types and each of them accomplish different purposes These are the types of indexes available in MySQL alone for the full list of possible index types refer to the documentation B Tree indexes these are the indexes that are used together with search queries that search for exact matches of data R Tree or spatial indexes can be used to index geospatial geographical data Covering indexes that cover all of the columns that a query is using allowing a database to read the index instead of the data itself which is a faster process Partial indexes that cover a part of the column that a specific query is using such indexes are frequently used to save space on the disk Fulltext indexes that can be used to help developers run fulltext search operations on data sets Indexes speed up reading SELECT operations but slow down all of the other operations INSERT DELETE and UPDATE queries in return When and How to Index The most frequent question regarding indexes is the time that s best to index data And the answer to this question is pretty straightforward really you should index data as soon as you feel your SELECT queries grinding to a halt or as soon as you have a lot more data than usual rows and above is a good starting point To index or not to index also heavily depends on your disk indexes take up space so if you re indexing millions of rows expect the indexing process to take a toll on the disk space and to take longer than usual Take a look at this table Information about a table in DbVisualizerIn this case around rows would be the perfect time to think about indexing the data has space to grow but at the same time the row count isn t insignificant In most cases to add an index you will make use of the CREATE INDEX or the ALTER TABLE query they aren t symlinks but whether you run a query like CREATE INDEX idx name column name or ALTER TABLE demo table ADD INDEX idx name column name shouldn t make much of a difference just bear in mind that ALTER TABLE queries work a little differently than ADD INDEX queries do if your table is bigger they make a copy of the table on the disk copy all of the data to it make the requested changes then swap the original table with the table that the DBMS created that will take up time as well Anyway add indexes with the ALTER or CREATE INDEX queries if you add them using DbVisualizer it will also tell you the time that the queries take and the status of them if the status is FAILED go back and check on what went wrong then run the query again Successful and Failed Queries in DbVisualizer What Type of Index to Choose After you ve decided what and when you will index it s time to decide what type of an index you should choose for your specific use case In many cases you will most likely be using B Tree indexes they are the most frequently used type of an index In other cases though your decision may be influenced by The space available on the disk if you re low on disk space use prefix indexes They will let you index a prefix of the column The type of data that your database holds if you re holding geographical data use spatial indexes The specific scenario that you want your databases to adhere to If you want to use fancy queries with wildcard support searching in the boolean mode etc you would need to use full text indexes If you want to save disk space you will use prefix indexes If you re working with the types of storage engines that store data in the memory and want to quickly read the data consider using hash indexes If you re working with geographical data you may need to use spatial R Tree indexes Different types of indexes are defined in different ways some of them can be seen below but for most of us ordinary B Tree indexes will do the trick Prefix indexes are defined by defining a prefix like so the number defines the characters to index Prefix Indexes in MySQLFulltext indexes are defined by specifying a FULLTEXT type Fulltext indexes in MySQLColumns can also have more than one type of index on them at once to satisfy multiple types of queries at the same time DbVisualizer and IndexesOnce your indexes have been added go back into the overview of your table click on your database management system then expand the database in question then head over to the Tables Finally click on the Indexes tab below the table itself to get ahold of all of the details img alt Observing indexes in DbVisualizer lt br gt height src dev to uploads s amazonaws com uploads articles itquqajofidzpe png width Fulltext indexes in MySQLNot only will DbVisualizer tell you what table holds what kind of an index it will tell you many more details related to the index itself including The name of the index and the column it s onWhether the index is made in an ascending or descending orderAll about the index cardinality how many unique values does the index hold Basically you will be able to observe everything that s necessary about the index itself most of the details presented in this tab will be necessary for those who know a little bit about databases themselves or those who are solving issues relating to query performance when indexes are in use Query Performance and IndexesAs we ve already noted indexes are only necessary to improve the performance of reading data they improve the performance of SELECT queries How many times the query performance will be improved though is directly dependant on your queries themselves to maximize the performance of your queries when they re using indexes aim to make your queries as simple as possible that is Return as few rows as possible switch SELECT to SELECT column Avoid JOINing data where possible Avoid OR queries where possible OR means “also think about… which slows down performance Subqueries also slow queries down due to the resources so be vary of that If necessary feel free to use them but when using them make sure that the subquery is using indexes as well Finally bear in mind that not all queries will use indexes you ve defined in the first place make use of the EXPLAIN keyword in database management systems to guide you to the light as a rule of thumb define the column that is indexed straight after the WHERE part of the query to ensure that your query is actually using the index and you should be good to go Also bear in mind that indexes will slow down INSERTs UPDATEs and DELETEs due to the fact that data needs to be updated together with the index when it s in use if you re using an index you should allocate more time for such operations as well Finally keep in mind that database maintenance has an impact on your query performance as well we recommend using SQL clients such as DbVisualizer to gain a deeper insight into your queries and your database instance itself your database will thank you after a while SummaryIn this blog we ve walked you through the importance of using indexes in database management systems Most of the examples provided were centered around MySQL and its counterparts such as Percona Server and MariaDB but the concept remains the same indexes speed up SELECT operations at the same time slowing down UPDATEs DELETEs and INSERTs Indexes have multiple types each being able to solve a different problem so before using them dig into these as well do know the risks involved and you should be good to go When improving query performance with indexes keep in mind that SQL clients like DbVisualizer can also help you solve problems related to maintenance and upkeep of your databases grab a free trial and try it today come back to the blog to learn more about databases in a while and until next time About the authorLukas Vileikis is an ethical hacker and a frequent conference speaker He runs one of the biggest amp fastest data breach search engines in the world BreachDirectory com frequently speaks at conferences and blogs in multiple places including his blog over at lukasvileikis com |
2023-05-26 07:28:24 |
海外TECH |
DEV Community |
A Comprehensive Guide of React Unit Testing |
https://dev.to/refine/a-comprehensive-guide-of-react-unit-testing-18bh
|
A Comprehensive Guide of React Unit TestingAuthor Chidume Nnamdi IntroductionUnit testing is a crucial step in the software development process where developers meticulously examine the smallest functional components known as units to ensure their proper functioning This process involves thorough testing conducted by software developers and occasionally by QA personnel as an integral part of the development lifecycle Unit testing helps us have faith and strong faith at that that our software works well and in the most bizarre use cases Users would not want bug ridden software Once users find glitches and bugs in software they lose hope and if the bugs and glitches are not fixed immediately they might abandon the software altogether So we see that bugs contribute a lot to how software progress in the market Sometimes it s difficult to test and cover all use cases before the software is deployed but unit testing helps us test different independent units of our software Making sure that they are working correctly and will stand the test of time Let s see an example of how unit testing is important Let s say we have a add function in an application that we use in our calculator application This add function accepts two parameters and these parameters should be a number Now in the real world users might input words and characters or even symbols this will cause our application to glitch because we did not know that users might enter inputs other than numbers But with unit testing of the add function before deployment we would have caught this and refactored the add function to handle these scenarios So we see how unit testing is very crucial in the software development of any application So in that unit testing has been a must in companies developers must write tests in any feature they build in their application otherwise the software will be deemed a risk Nobody wants to lose customers So many unit testing tools have sprung up in recent years making unit testing in the React framework very easy In addition almost all programming has testing frameworks or tools built for them The popular ones are JUnit PHUnit Jasmine Mocha etc In this article we will learn all about unit testing in the React js framework We will learn how to unit test our component down to hooks and Context Setting up a testing environmentLet s create a new React project create react app test prjcd test prjThe testing tools that we will use are Jest and React Testing Libary Jest This is a popular testing library built by Facebook It has simple APIs that make testing very easy React Testing Libary This is a testing built on top DOM Testing Library that gives us the power to test React components It comes with React project scaffolded with the create react app tool if it is not present you can install it using npm install save dev testing library react To install Jest we run the command npm install save dev jest The next question is Where do we write the test Tests are written in js ts files but the js ts are preceded with test so that Jest and React Testing Library can pick them up because that is the only we tell the testing libraries that those are our test files So our test file for the add function will be add test js To run the test files we will have to add a test section to the scripts section in our package json scripts test jest Now when we run the command npm run test or yarn run test Jest will search and collect all files with test js ts tsx tsx in their names and run them in a testing environment We can group the test files under a folder called tests Jest we look for the folders in your application and run the test js ts tsx tsx in them Writing unit tests for React componentsWe will learn how to test a basic React component Let s write a component that renders Hello World and test that the component actually renders the popular greeting import React from react const HelloWorld gt return lt div gt Hello World lt div gt export default HelloWorld Now we will create a test file HelloWorld test js test renders Hello World text gt const getByText render lt HelloWorld gt const helloWorldElement getByText Hello World expect helloWorldElement toBeInTheDocument In this test case we render the HelloWorld component using the render function provided by React Testing Library We then use the getByText function to retrieve the element that contains the Hello World text Finally we use the toBeInTheDocument matcher to check if the element is present in the rendered component The render function is used to render the component in a DOM this is similar to the DOM in the browser Once this is done we can then test the component using DOM API like functions provided by the React Testing Library The getByText function searches the rendered DOM for the string passed to it The toBeInTheDocument function is used to test if the DOM object it was called exists in the DOM We can assign a test id to elements in our component so we can pinpoint them directly by using the getTestById function provided by React Testing Library import React from react const HelloWorld gt return lt div data testid hello world gt Hello World lt div gt export default HelloWorld See the use of data testid property in the div element there To get the div element we will call the getByTestId function passing in the value of the data testid to the function getByTestId hello world This returns the HTMLElement instance of the div element and then we can test the Hello World text node using the textContent DOM property import React from react import render from testing library react import HelloWorld from HelloWorld test renders Hello World text using getByTestId gt const getByTestId render lt HelloWorld gt const helloWorldElement getByTestId hello world expect helloWorldElement toBeInTheDocument expect helloWorldElement textContent toBe Hello World We use getByTestId hello world to query the element with the data testid attribute set to hello world Then we assert that the element is in the document and verify its textContent to be Hello World using the toBe matcher Now let s move over to testing and firing events in components Test firing eventsLet s say we have a Counter application that updates the DOM with the click of a button import React useState from react const Counter count gt const increment setIncrement useState const handleIncrement gt setIncrement increment return lt div gt lt p gt Increment increment lt p gt lt button onClick handleIncrement gt Increment lt button gt lt div gt export default Counter Now we have a state increment that holds the state of the application and it is displayed in the DOM The Increment button when clicked increases the state increment by one So let s write a test for this component to make sure that the increment state is increased when the Increment button is clicked So to test this we will need to somehow fire a click event on the Increment button but how can we do this We will see below import React from react import render fireEvent from testing library react import Counter from Counter test increments count on button click gt const getByText render lt Counter gt const incrementElement getByText Increment const buttonElement getByText Increment fireEvent click buttonElement expect incrementElement textContent toBe Increment React Testing Library has a click method set to the DOM instance of an element that simulates the click event as if it was actually clicked by a user See that we got the DOM instance of the button by calling this getByText Increment then we called the click method on its instance this will fire the click event on the button causing the increment state to be increased by one then we will thereafter to see if the state was really updated See in the last line we got the text node of the div element and expect it to be Increment Now let s move over to testing states and props in components State and props of the componentsThis entails testing that the current value of a state is updated correctly when an action is executed Let s say we have a state import React useState from react const Counter count gt const count setCount useState const increment gt setCount count return lt div gt lt p gt Count lt span data testid count gt count lt span gt lt p gt lt button data testid button onClick increment gt Increment lt button gt lt div gt export default Counter We have a state count and it is displayed in the DOM in the p element The Increment button when clicked increments the state of the count by and this in turn makes the component re render and displayed the updated value of the count state Let s write a test that ensures that the count state is updated when the setCount is called import React from react import render fireEvent from testing library react import Counter from Counter test increments count on button click gt const getByText render lt Counter gt const countElement getByTestId count const buttonElement getByTestId button fireEvent click buttonElement expect incrementElement textContent toBe We are now familiar with what is being done here We expect the last code to pass because after the button has been clicked the state count should be incremented to Let s test for props passed to a component We know that props are attributes passed to components import React useState from react const Counter count gt return lt div gt lt p gt Count lt span data testid count gt count lt span gt lt p gt lt div gt export default Counter We have this component expecting a value to be passed to it via count attribute in its props object So now let s write a test for it to make sure a count attribute passed to the Counter component is displayed import React from react import render from testing library react import Counter from Counter test increments count on button click gt const getByText render lt Counter count gt const countElement getByTestId count expect incrementElement textContent toBe Here we rendered the Counter component passing a value of via its count props Then we got hold of the p element where the props will be rendered Then we expect it to be the value Open source enterprise application platform for serious web developersrefine new enables you to create React based headless UI enterprise applications within your browser that you can preview tweak and download instantly By visually combining options for your preferred React platform UI framework backend connector and auth provider you can create tailor made architectures for your project in seconds It feels like having access to thousands of project templates at your fingertips allowing you to choose the one that best suits your needs Mocking function callsDuring testing we might not really want an actual function to be called based on some factors For example the function might have a number of calls set on it The only way to go about this is to mock that function ie to create a dumb version function of that actual function We do this in Jest by calling the fn API This creates a mock function and returns it const mockFn jest fn We can then test the number of times the function was called and the return value of the function and also Jest provides in an array the arguments passed to the function each time it was called Let s see an example const Test done gt return lt div gt lt button onClick done gt Call DONE lt button gt lt div gt We have a simple component here it accepts a function in its props object via done property This done props function is called when the Call DONE button is clicked Now we want to test the component to see if the done props passed to the component is called when the Call DONE button is clicked To test this we will need to pass a mock function to the done props of the component Let s see below how we can do it import React from react import render from testing library react import Test from Test test test mock function props is called gt const fn jest fn const getByText render lt Test done fn gt const button getByText Call DONE button click expect fn mock calls toBe button click expect fn mock calls toBe We created a mock function fn by calling the fn function from the jest object We passed the mock function to the Test component in a done attribute Next we got the handle of the Call DONE button and fire a click event on it This will call the mock function once that s why in the next line we expect the mocked function to be called once Next we fired the click event and this time we expected the function to be called again Testing React hooksNow we will test React custom hooks In testing React hooks we will be verifying the behavior and state changes of a component that uses hooks Let s say we have a custom hook called useCounter that manages a counter value and provides functions to increment and decrement it import useState from react const useCounter gt const count setCount useState const increment gt setCount prevCount gt prevCount const decrement gt setCount prevCount gt prevCount return count increment decrement export default useCounter The above custom hook gives us the ability to handle our count state from one place It returns the count state the increment function and the decrement function We will destructure all these inside the component and use it to manage and manipulate the count state Now let s write a test case for this custom hook import renderHook act from testing library react hooks import useCounter from useCounter test should increment and decrement counter correctly gt const result renderHook gt useCounter const count increment decrement result current expect count toBe act gt increment expect count toBe act gt decrement expect count toBe In this test case we use the renderHook function from the testing library react hooks package to render the useCounter hook The result object from renderHook gives us access to the current state and functions returned by the hook The result is an object that contains a property called current The value of this current is an object that contains the return value of the useCounter hook From this current object we destructured all the objects returned by the useCounter hook We assert that the initial value of the count state is Then we use the act function to perform actions on the hook Within act we call the increment function and assert that the count state is incremented to Similarly we call the decrement function and verify that the count state is decremented to The act function is used to wrap asynchronous or state updating code that affects React components It ensures that all state updates are properly processed and reflected in the component before making assertions You see how easy it is to test custom hooks using the renderHook function we had no need of using the custom hook inside of a component just to test it Testing asynchronous operationsAsynchronous operations involve handling promises asynchronous functions and async await syntax The most common example of an async operation in a React component is the fetching of data over HTTP HTTP calls are async operations in the sense that it does not stop the flow of the code execution instead it is executed in parallel with the main code Let s see a component that on render makes an HTTP call to an endpoint and then renders the result of the fetch import React useState useEffect from react const AsyncComponent gt const data setData useState null useEffect gt const fetchData async gt const response await fetch const result await response json setData result fetchData return lt div gt data data message Loading lt div gt export default AsyncComponent This component fetches data from and renders it Now we want to test this component but we don t want the component to make an actual HTTP call to the endpoint So what do we do We have to mock the fetch call Also the fetch call is an async op what do we do The React Testing Library has a function waitFor this function waits for an async operation to complete before the code execution flow resumes We can pass a callback to it that executes after the async operation completes Let s see below import React from react import render waitFor from testing library react import AsyncComponent from AsyncComponent test renders fetched data after async call async gt const mockData message Test Message Mock the fetch API jest spyOn window fetch mockImplementation gt Promise resolve json gt Promise resolve mockData const getByText render lt AsyncComponent gt Assert that Loading is initially rendered expect getByText Loading toBeInTheDocument Wait for the async operation to complete await waitFor gt expect getByText mockData message toBeInTheDocument Restore the original fetch implementation window fetch mockRestore In this test case A mock data object mockData is defined to simulate the data returned from the API The fetch function is mocked using jest spyOn and mockImplementation It returns a resolved promise that resolves to an object with a json function that in turn resolves to mockData The render function is used to render the AsyncComponent The initial rendering displays Loading which is verified using expect and getByText The waitFor function from testing library react is used to wait for the asynchronous operation to complete Within the callback of waitFor we assert that the fetched data mockData message is rendered in the component Finally the original implementation of fetch is restored using window fetch mockRestore to ensure other tests are not affected By using await and waitFor you can test and assert the behavior of asynchronous operations in our React components It allows us to verify that the correct data is fetched and rendered after the asynchronous operation is completed Testing React Context APIIn testing React Context API we will verify that the components correctly consume and provide values from the context Let s say we have a context called ThemeContext that provides a theme value to consuming components import React createContext useContext from react const ThemeContext createContext export const ThemeProvider children gt const theme light return lt ThemeContext Provider value theme gt children lt ThemeContext Provider gt export const useTheme gt useContext ThemeContext We created a global context here that passes down a theme down to its children The ThemeProvider does that see how encloses the children element between its tag We created a custom hook that we can use to get the ThemeContext see that it utilizes the useContext hook from React to consume the theme value from the ThemeContext It returns the current value of the ThemeContext Now let s write a test case for a component that consumes the ThemeContext using the useTheme hook import React from react import render from testing library react import ThemeProvider useTheme from ThemeContext const ThemeConsumer gt const theme useTheme return lt div gt theme lt div gt test renders theme value from the context gt const getByText render lt ThemeProvider gt lt ThemeConsumer gt lt ThemeProvider gt expect getByText light toBeInTheDocument Here we rendered the ThemeConsumer component wrapped within the ThemeProvider to provide the theme value Next we used the getByText function to query the DOM for the rendered text We expect to have a text node with the value light in the DOM because the ThemeConsumer must have gotten the theme value and rendered it Next let s see how we can test routing in React Testing React RouterIts quite tricky how this can be done but believe me it s very easy and straightforward To test React Router all we have to do is to load a particular URL and verify that the associated component is rendered on the DOM Let s say we have two routes home and about in our application and home route is mapped to Home component and the about route is mapped to the About component const Home gt return lt div gt This is the Home component lt div gt export default Home About jsconst About gt return lt div gt This is the About component lt div gt export default AboutLet s set up the routing import React from react import BrowserRouter as Router Route Link Switch from react router dom import Home from Home import About from About const App gt return lt Router gt lt nav gt lt ul gt lt li gt lt Link to home gt Home lt Link gt lt li gt lt li gt lt Link to about gt About lt Link gt lt li gt lt ul gt lt nav gt lt Switch gt lt Route exact path home component Home gt lt Route path about component About gt lt Switch gt lt Router gt export default App Now let s write the test cases import React from react import render screen from testing library react import BrowserRouter as Router from react router dom import App from App test renders home component when visiting the home route gt render lt Router initialEntries home gt lt App gt lt Router gt expect screen getByText This is the Home component toBeInTheDocument test renders about component when visiting the about route gt render lt Router initialEntries about gt lt App gt lt Router gt expect screen getByText This is the About component toBeInTheDocument You understand the trick we did there See that in the first render we rendered our App component enclosed by the Router component and passed the URL home to it Now according to our route mapping this is supposed to render the Home component and the component will render the text This is the Home component in the DOM So in the next line we expect to see the text This is the Home component in the DOM Easy To test for the about route we did the same thing but this time we passed about URL so we know that the About will be rendered this time and we expect to have This is the About component text node in the DOM These test cases verify that the components Home and About are rendered correctly based on the route configuration Snapshot testingSnapshot testing is quite different from what we have seen in this article This type of testing is classified as output comparison testing In the case of React component snapshot testing the UI of the component is taken first and saved then on subsequent testing a current snapshot of the component is taken and compared with the previous snapshot to check for changes that may cause breaks Let s see an example import React from react const Button text onClick gt return lt button onClick onClick className button gt text lt button gt export default Button To create a snapshot test for this component you can write a test case using the toMatchSnapshot matcher import React from react import render from testing library react import Button from Button test Button component matches snapshot gt const asFragment render lt Button text Click me onClick gt gt expect asFragment toMatchSnapshot Here the render function renders the Button component with some props The asFragment function is then used to retrieve the rendered component as a snapshot The toMatchSnapshot matcher compares the rendered output with the previously saved snapshot If a snapshot doesn t exist Jest creates a new one If a snapshot exists and there are no changes the test passes If there are differences between the snapshot and the current output Jest highlights the differences and the test fails When you run this test for the first time Jest will create a snapshot file e g Button test js snap containing the rendered output On subsequent test runs Jest compares the rendered output with the snapshot and reports any changes If you intentionally make changes to the component s output and want to update the snapshot you can run Jest with the updateSnapshot flag to update the snapshot file jest updateSnapshot ConclusionWe covered a lot in this article We started with introducing unit testing in software development as a whole Then next we learned how to set up a testing environment in React project and from there we installed the testing tools and libraries Further down we learned how to write tests for basic React components how to fire events on elements in a testing env and how to test states and props We advanced a little exploring deep concepts we learned how to test React Context powered components Routing system and snapshot testing |
2023-05-26 07:01:37 |
金融 |
JPX マーケットニュース |
[JPX総研]東証REIT用途別指数の構成銘柄選定の誤りと今後の対応について |
https://www.jpx.co.jp/news/6030/20230526-01.html
|
銘柄 |
2023-05-26 16:20:00 |
金融 |
日本銀行:RSS |
資金循環統計の遡及改定(予定)について |
http://www.boj.or.jp/statistics/outline/notice_2023/not230526a.pdf
|
遡及 |
2023-05-26 16:50:00 |
金融 |
日本銀行:RSS |
対外資産負債残高(年次公表データ)等 2022年末、2021年末年次改訂値 |
http://www.boj.or.jp/statistics/outline/notice_2023/not230526b.htm
|
対外資産負債残高 |
2023-05-26 16:50:00 |
金融 |
日本銀行:RSS |
日本銀行政策委員会月報(令和5年4月号) |
http://www.boj.or.jp/about/organization/policyboard/pb_geppo/pbgp2304.pdf
|
日本銀行政策委員会 |
2023-05-26 16:30:00 |
海外ニュース |
Japan Times latest articles |
As competition heats up, Tokyo’s international schools spruce up facilities |
https://www.japantimes.co.jp/news/2023/05/26/national/international-schools-renovation-competition/
|
As competition heats up Tokyo s international schools spruce up facilitiesWith families looking for an international learning experience having more options renovating facilities is top of the to do list for several institutions |
2023-05-26 16:20:50 |
ニュース |
BBC News - Home |
Closing baby unit was considered over safety concerns |
https://www.bbc.co.uk/news/uk-england-kent-65709193?at_medium=RSS&at_campaign=KARANGA
|
closing |
2023-05-26 07:37:29 |
ニュース |
BBC News - Home |
Mortgage rates rise after inflation surprise |
https://www.bbc.co.uk/news/business-65713905?at_medium=RSS&at_campaign=KARANGA
|
climate |
2023-05-26 07:51:57 |
ニュース |
BBC News - Home |
John Caldwell: Eleven arrested over shooting of police officer |
https://www.bbc.co.uk/news/uk-northern-ireland-65711267?at_medium=RSS&at_campaign=KARANGA
|
operation |
2023-05-26 07:25:51 |
ニュース |
BBC News - Home |
Charles Schwab Challenge: England's Harry Hall holds three-shot lead but American club pro Michael Block bottom of leaderboard after round one |
https://www.bbc.co.uk/sport/golf/65718611?at_medium=RSS&at_campaign=KARANGA
|
Charles Schwab Challenge England x s Harry Hall holds three shot lead but American club pro Michael Block bottom of leaderboard after round oneEngland s Harry Hall hits a career best eight under par to hold three shot lead at the Charles Schwab Challenge but Michael Block is bottom of the leaderboard on over |
2023-05-26 07:34:10 |
ニュース |
Newsweek |
米テック企業「自由で働きやすい」は大間違い? 実は労働者に厳しい実態が続々と明らかに |
https://www.newsweekjapan.jp/stories/world/2023/05/post-101723.php
|
|
2023-05-26 16:51:00 |
IT |
週刊アスキー |
食欲が落ちやすい暑い夏をカレーで元気に乗りきる ホテルニューグランド「ザ・カフェ」にて2種の新作カレーを期間限定販売 |
https://weekly.ascii.jp/elem/000/004/138/4138426/
|
期間限定 |
2023-05-26 16:50:00 |
IT |
週刊アスキー |
旬のフルーツを使ったタルトなどを提供! フルーツタルト専門店「ラ・メゾン アンソレイユターブル パティスリー」京王百貨店新宿店にオープン |
https://weekly.ascii.jp/elem/000/004/138/4138411/
|
京王百貨店 |
2023-05-26 16:15:00 |
IT |
週刊アスキー |
さくらインターネット、ブラウザーから無料で利用できるシェル環境「さくらのクラウドシェル」 |
https://weekly.ascii.jp/elem/000/004/138/4138428/
|
開発者 |
2023-05-26 16:45:00 |
マーケティング |
AdverTimes |
広告制作の実績・経験が得られる講座-コピーライター養成講座卒業制作が天神地下街で掲出中! |
https://www.advertimes.com/20230526/article420781/
|
卒業制作 |
2023-05-26 07:57:46 |
マーケティング |
AdverTimes |
メディア企業が広告商品開発に活用できる資源とは? 「Advertising Week Asia2023」連動企画② |
https://www.advertimes.com/20230526/article420764/
|
メディア企業が広告商品開発に活用できる資源とは「AdvertisingWeekAsia」連動企画②ニューヨーク、ロンドンをはじめとした世界大陸で開催されているマーケティングコミュニケーションのプレミアイベント「AdvertisingWeekアドバタイジング・ウィーク」のアジア版である「AdvertisingWeekAsiaアドバタイジング・ウイーク・アジア」が月日から開催される。 |
2023-05-26 07:41:55 |
コメント
コメントを投稿