Jest
JavaScript Framework สำหรับเอาไว้เขียน Test เป็น Open Source ที่พัฒนาโดย Facebook
install
npm install --save-dev jest @types/jest
#package.json
script: {
"test": "jest --coverage",
"test:watch": "jest --watch",
}
#jest.config.js
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
setupFiles: ['dotenv/config'],
};
โฟลเดอร์เทสเรา จะไว้ในชื่อ __tests__
ก็ได้ หรือไว้ข้างนอกก็ได้เช่นกัน ขอแค่มีชื่อ .spec
หรือ .test
ต่อท้าย โดยเราสามารถตั้งชื่อได้โดยใช้ชื่อไฟล์ต่อท้าย เช่น app.test.js
หรือ app.spec.js
#app.test.js
const { getScore } = require('./app')
describe('Score', () => {
it('should get A', () => {
const result = getScore()
// Assertion
expect(result).toEqual('A')
})
});
เริ่มเขียน Test
Jest API Block Scope
describe: ใช้ระบุ test group หรือจะเรียกว่า test suite ก็ได้ครับ โดยเราอาจจะแบ่งตาม API Endpoints ก็ได้
it หรือ test: ใช้ระบุ scope ของ test ของเรานั่นเอง
beforeAll: ใช้ระบุ test suite setup ต่างๆ ที่จะทำก่อน 1 ครั้งเริ่ม test ทุกข้อ
beforeEach: ใช้ระบุ test case setup ที่จะทำก่อนเริ่มเทสทุกข้อ
afterEach: ใช้ระบุ test case teardown ที่จะทำหลังเทสทุกข้อ
afterAll: ใช้ระบุ test suite teardown ที่จะทำหลังจากรันเทสครบทุกข้อแล้ว 1 ครั้ง
ยังมี API อื่นๆ ที่สามารถใช้งานได้ สามารถอ่านรายละเอียดเต็มๆ ได้ที่ https://jestjs.io/docs/api เลย
Mock Function
it('should works with jest.fn() and mockResolvedValue', async () => {
let myMock = fetchSomeData
myMock = jest.fn()
myMock.mockResolvedValue('success from mock data')
await expect(myMock()).resolves.toEqual('success from mock data')
})
const app = { fetchSomeData : ()=>{ return 'success' } } it('spyOn and custom response', async () => { const spy = jest.spyOn(app, 'fetchSomeData').mockResolvedValue('fail') const isLoggedIn = await app.login() expect(isLoggedIn).toBe(false) expect(spy).toHaveBeenCalled() app.fetchSomeData.mockRestore() })
เราทำการ mock function ขึ้นมา เพื่ออะไร เพื่อเอาไว้เทส function โดยที่เราอยากเปลี่ยนแปลงค่าของ function ที่เราต้องการ เช่น fetchSomeData() function จริงๆ มัน return success เราอยากจะเปลี่ยนเป็น error เป็น hello world หรืออื่นๆ เพื่อเทส เราก็ใช้ mock ได้ โดยไม่จำเป็นต้องแก้ไขโค๊ดเรา
jest.fn() : mock function
สั่งให้ mock function return กลับมาเป็น "hello world"
jest.fn().mockReturnValue('hello world')
สั่งให้ mock function return กลับมาเป็น Promise("hello world")
jest.fn().mockResolvedValue('hello world')
jest.spyOn([object], ["function mane"]) : คล้ายๆกับ mock function ด้วย jest.fn() แต่สามารถ tracking object ได้ รวมถึง restore mock หรือกลับไปใช้ function จริงที่ไม่ได้ mock ได้
spy function 'fetchSomeData' และ return 'fail'
jest.spyOn(app, 'fetchSomeData').mockResolvedValue('fail')
.toHaveBennCalled()
เช็คว่า spy function ของเราถูกเรียกรึป่าว
const spy = jest.spyOn(app, 'fetchSomeData').mockResolvedValue('fail')
expect(spy).toHaveBeenCalled()
อ่านเพิ่มเติมได้ที่ https://jestjs.io/docs/mock-functions
Last updated