نحوه یونیت تست برنامه های nodejs یا جاواا اسکریپت

درود،بنده می خواستم بدونم چجوری برنامه های جاوا اسکریپت رو خصوصا وقتی دارم با nodejs کار می کنم تست کنم یا براش یونیت تست بنویسم.

کلا می خوام بدونم پروسه نوشتم یونیت تست در nodejs چجوریه و چه روندی رو باید طی کنم.

پاسخ ها

sokanacademy forum
کاربر سکان آکادمی 5 سال پیش

سلام خسته نباشید

پیشنهاد من برای نود جی اس استفاده از jest هستش من یک مثال ساده براتون میزنم تا با نحوه تست آشنا شوید سپس در صورت تمایل گوگل کنید :)

کلاس زیر را در نظر بگیرید: نام فایل : block.js

const SHA256 = require('crypto-js/sha256');

class Block{
 constructor(timestamp, lastHash, hash, data){
 this.timestamp = timestamp;
 this.lastHash = lastHash;
 this.hash = hash;
 this.data = data;
 }

 toString(){
 return `
 Block -
 Timestamp: ${this.timestamp}
 Last Hash: ${this.lastHash.substring(0, 10) + `...`}
 Hash : ${this.hash.substring(0, 10) + `...`}
 Data : ${this.data}`;
 }

 static genesis(){
 return new this('Genesis time', '????', 'fshf389y9fsjf', []);
 }

 static mineBlock(lastBlock, data){
 const timestamp = Date.now();
 const lastHash = lastBlock.hash;
 const hash = Block.hash(timestamp, lastHash, data);
 return new this(timestamp, lastHash, hash, data);
 }

 static hash(timestamp, lastHash, data){
 return SHA256(`${timestamp}${lastHash}${data}`).toString();
 }
}

module.exports = Block;

حال یونیت تست خیلی ساده اون به صورت زیر است: نام فایل : block.test.js

const Block = require('./block');

describe('Block', () => {
 let data, lastBlock, block;

 beforeEach(() => {
 data = 'bar';
 lastBlock = Block.genesis();
 block = Block.mineBlock(lastBlock, data);
 });

 it('sets the `data` to match the input', () => {
 expect(block.data).toEqual(data);
 });

 it('sets the `lastHash` to match the hash of the last block', () => {
 expect(block.lastHash).toEqual(lastBlock.hash);
 });


});

توجه داشته باشید که در فایل json پروژه تون توی قسمت test بنویسید jest --watchAll

اطلاعات بیشتر در وبسایت جست!

online-support-icon