Fundumentals of Testing in javaScript

分享下react-test-library 做者寫的一系列測試文章,教你如何寫測試。包含視頻,此係列會不斷的更新.這個系列一共有100多個視頻。node

Throw an Error with a Simple Test in JavaScript

In this lesson, we’ll get the most fundamental understanding of what an automated test is in JavaScript. A test is code that throws an error when the actual result of something does not match the expected output.react

Tests can get more complicated when you’re dealing with code that depends on some state to be set up first (like a component needs to be rendered to the document before you can fire browser events, or there needs to be users in the database). However, it is relatively easy to test pure functions (functions which will always return the same output for a given input and not change the state of the world around them).git

提取碼: kewv
複製代碼

觀看視頻github

Codeless

Transcript

We have a bug in the sum function. It's doing subtraction instead of addition. We could easily fix this, but let's go ahead and write an automated test that can make sure that this bug never surfaces again.ide

An automated test in JavaScript is code that throws an error when things are unexpected. Let's do that. Let's get our result from the sum of three and seven.測試

simple.jsui

const result = sum(3, 7)
複製代碼

We will say our expected is 10. We can say if the result is not equal to the expected value, then we can throw a new error that says, "Result is not equal to expected."this

const expected = 10
if (result !== expected){
    throw new Error(`${result} is not equal to ${expected}`)
}
複製代碼

To run this, we can run node lessons/simple.js.spa

We will get our error, "-4 is not equal to 10."

If we replace this with addition and run that again, our script passes without throwing errors. This is the most fundamental form of a test.

const sum = (a, b) => a + b
複製代碼

Let's go ahead and add another test for subtract. I am going to change this from const to let.

const subtract = (a, b) => a - b
複製代碼

We will say, result is now equal to subtract of seven and three, and our expected is now equal to four."

result = subtract(7, 3)
expected = 4
複製代碼

We will just copy and paste this here.

if (result !== expected){
    throw new Error(`${result} is not equal to ${expected}`)
}
複製代碼

Save that and run our script again. It passes without error. In review, this is the most fundamental form of a test in JavaScript. It's simply a code that will throw an error when the result is not what we expect.

Let's go ahead and break this again. We'll run that script again. We're getting an error message. The Javascript testing framework is to make that error message as useful as possible so we can quickly identify what the problem is and fix it.

star此項目

相關文章
相關標籤/搜索