高橋  花子

高橋 花子

1661076240

Jasmine で単体テストを開始する方法

前回の記事では、純粋関数の単体テストの疑似コード例を示しました。その記事への回答として、素晴らしい質問を受け取りました。では、コードのテストを開始するにはどうすればよいでしょうか? テストの同じ単純なケースをより実用的に見てみましょう。

コードベースを入手する

サンプルコードのリポジトリを用意しました。主な内容はpure-functions.js次のとおりです。

export function greet(name, surname) {
  return `Hello ${name} ${surname}!`;
}

export function calculateDiscountedPrice(originalPrice, discount) {
  return originalPrice - originalPrice * discount;
}

export function power(base, exponent) {
  return base ** exponent;
}

ご覧のとおり、コードは単純です。

ローカルで新しいパッケージを作成する場合の注意事項

リポジトリ全体ではなくコード ファイルをコピーする場合は、問題が 1 つあります。次のことを行う必要があります。

  1. 次を使用してパッケージを生成します。npm initしたがって、ノードの依存関係は現在のフォルダーにインストールされます。
  2. に追加して、コードをmodulepackage.jsonに切り替えます。
{
  …
  "type": "module",
  …
}

私のレポでそれがどのように行われたかを見ることができます。

ジャスミンをインストール

テストするコードは、ブラウザまたはノードで同じように機能します。簡単にするために、ノードでテストしてみましょう。まず、ジャスミンをインストールする必要があります。そのためには、公式ドキュメントに従いましょう:

$ npm install --save-dev jasmine #1

$ npx jasmine init #2

コマンドは次の機能を実行します。

  1. Jasmine を開発依存としてインストールする
  2. で基本設定を生成しますspec/support/jasmine.json
{
  "spec_dir": "spec",
  "spec_files": [
    "**/*[sS]pec.?(m)js"
  ],
  "helpers": [
    "helpers/**/*.?(m)js"
  ],
  "env": {
    "stopSpecOnExpectationFailure": false,
    "random": true
  }
}

package.json最後に、更新してテスト コマンドを構成しましょう。

{
  …
  "scripts": {
    "test": "jasmine"
  },
  …
}

実行中 (なし) テスト

この時点で、単一のテストを実施するのではなく、必要な構成をすべて完了しているはずです。期待どおりに動作するかどうかを見てみましょう。

$ npm test

> how-to-unit-test@1.0.0 test
> jasmine

Randomized with seed 10285
Started


No specs found
Finished in 0.002 seconds
Incomplete: No specs found
Randomized with seed 10285 (jasmine --random=true --seed=10285)

試験例

簡単なテストを追加しましょう。./spec/pure-functions.spec.jsJasmine 規則に一致する新しいファイルを作成します。

  • ./spec生成された構成の次の行に設定されている内容に従って、フォルダー内にあります。"spec_dir": "spec",
  • spec.js-で確立された別の命名パターンで終わります"spec_files": ["**/*[sS]pec.?(m)js"

内部に入るコード./spec/pure-functions.spec.js:

import { greet } from "../pure-functions.js";

describe("greet", () => {
  it("should greet by name & surname", () => {
    expect(greet("Lorem", "Ipsum")).toEqual("Hello Lorem Ipsum!");
  });
});

コード:

  • import { greet } from "../pure-functions.js";-ソース コードから関数を取得します。"type": "module",この行は、 inがないと期待どおりに機能しませんpackage.json
  • describe("", <callback>)-関連するテストをラップして、より適切なエラー メッセージを表示します。
  • it("", <callback>)-個別テスト、
  • expect(<value>).<matcher>(<arguments>);-ジャスミンで期待を設定する方法です. ドキュメントでマッチャーを見つけることができます。

走る!

このテストの実行:

$ npm run test

> how-to-unit-test@1.0.0 test
> jasmine

Randomized with seed 09863
Started
.


1 spec, 0 failures
Finished in 0.004 seconds
Randomized with seed 09863 (jasmine --random=true --seed=09863)

最終コード

私の最終的なコードはこちらにあります

 ソース: https://javascript.plainenglish.io/how-to-start-unit-testing-with-jasmine-ff55fa230fb5

#jasmine #testing 

Jasmine で単体テストを開始する方法
顾 静

顾 静

1661076240

如何使用 Jasmine 开始单元测试

在我之前的文章中,我展示了单元测试纯函数的伪代码示例。在回复那篇文章时,我得到了一个很好的问题——那么我该如何开始测试我的代码呢?让我们更实际地看一下相同的简单测试案例。

获取代码库

我准备了一个包含示例代码的存储库。主要内容是pure-functions.js

export function greet(name, surname) {
  return `Hello ${name} ${surname}!`;
}

export function calculateDiscountedPrice(originalPrice, discount) {
  return originalPrice - originalPrice * discount;
}

export function power(base, exponent) {
  return base ** exponent;
}

如您所见,代码很简单。

如果你在本地创建一个新包,就会遇到问题

如果您想复制代码文件而不是整个存储库,那么有一个问题。您将需要:

  1. 生成一个包:npm init因此,您的节点依赖项安装在当前文件夹中。
  2. 通过添加以下代码将代码切换为模块package.json
{
  …
  "type": "module",
  …
}

你可以在我的 repo中看到它是如何完成的。

安装茉莉花

我们将要测试的代码将在浏览器或 Node 上以相同的方式工作。为简单起见,让我们在 Node.js 上进行测试。首先,我们需要安装 Jasmine。为此,让我们按照官方文档

$ npm install --save-dev jasmine #1

$ npx jasmine init #2

这些命令执行以下功能:

  1. 安装 Jasmine 作为开发依赖
  2. 生成基本配置spec/support/jasmine.json
{
  "spec_dir": "spec",
  "spec_files": [
    "**/*[sS]pec.?(m)js"
  ],
  "helpers": [
    "helpers/**/*.?(m)js"
  ],
  "env": {
    "stopSpecOnExpectationFailure": false,
    "random": true
  }
}

最后,让我们更新package.json配置测试命令:

{
  …
  "scripts": {
    "test": "jasmine"
  },
  …
}

运行(无)测试

此时,您应该已经完成​​了所有必要的配置,而不是一个单一的测试。让我们看看它是否按预期工作:

$ npm test

> how-to-unit-test@1.0.0 test
> jasmine

Randomized with seed 10285
Started


No specs found
Finished in 0.002 seconds
Incomplete: No specs found
Randomized with seed 10285 (jasmine --random=true --seed=10285)

示例测试

让我们添加一个简单的测试。我们将创建一个./spec/pure-functions.spec.js与 Jasmine 约定匹配的新文件:

  • 它位于./spec文件夹内 - 遵循生成配置的这一行中设置的内容:"spec_dir": "spec",
  • 它以spec.js-another 命名模式结束"spec_files": ["**/*[sS]pec.?(m)js"

里面的代码./spec/pure-functions.spec.js

import { greet } from "../pure-functions.js";

describe("greet", () => {
  it("should greet by name & surname", () => {
    expect(greet("Lorem", "Ipsum")).toEqual("Hello Lorem Ipsum!");
  });
});

代码:

  • import { greet } from "../pure-functions.js";- 从我们的源代码中获取函数。"type": "module",如果没有in ,这条线将无法按预期工作package.json
  • describe("", <callback>)-包装相关测试以获得更好的错误消息。
  • it("", <callback>)- 个人测试,
  • expect(<value>).<matcher>(<arguments>);-这就是我们在 Jasmine 中设定期望的方式。您可以在文档中找到匹配器

跑!

此测试运行:

$ npm run test

> how-to-unit-test@1.0.0 test
> jasmine

Randomized with seed 09863
Started
.


1 spec, 0 failures
Finished in 0.004 seconds
Randomized with seed 09863 (jasmine --random=true --seed=09863)

最终代码

你可以在这里找到我的最终代码。

 来源:https ://javascript.plainenglish.io/how-to-start-unit-testing-with-jasmine-ff55fa230fb5

#jasmine #testing 

如何使用 Jasmine 开始单元测试
Anne  de Morel

Anne de Morel

1661072520

Comment Démarrer Les Tests Unitaires Avec Jasmine

Dans mon article précédent , j'ai montré des exemples de pseudo-code de tests unitaires de fonctions pures . En réponse à cet article, j'ai reçu une excellente question, alors comment puis-je commencer à tester mon code ? Jetons un coup d'œil plus pratique au même cas simple pour les tests.

Obtenir la base de code

J'ai préparé un référentiel avec l'exemple de code. Le contenu principal est pure-functions.js:

export function greet(name, surname) {
  return `Hello ${name} ${surname}!`;
}

export function calculateDiscountedPrice(originalPrice, discount) {
  return originalPrice - originalPrice * discount;
}

export function power(base, exponent) {
  return base ** exponent;
}

Comme vous pouvez le voir, le code est simple.

Gotcha si vous créez un nouveau package localement

Si vous souhaitez copier le fichier de code au lieu de l'ensemble du référentiel, il y a un piège. Tu devras:

  1. Générez un package avec : npm initAinsi, vos dépendances de nœuds sont installées dans le dossier en cours.
  2. Changez le code en module , en ajoutant à package.json:
{
  …
  "type": "module",
  …
}

Vous pouvez voir comment c'est fait dans mon dépôt .

Installer Jasmin

Le code que nous allons tester fonctionnera de la même manière sur navigateur ou Node. Pour plus de simplicité, testons-le sur Node. Tout d'abord, nous devons installer Jasmine. Pour cela, suivons la documentation officielle :

$ npm install --save-dev jasmine #1

$ npx jasmine init #2

Les commandes exécutent les fonctions suivantes :

  1. Installer Jasmine en tant que dépendance de développement
  2. Générez la configuration de base dans spec/support/jasmine.json:
{
  "spec_dir": "spec",
  "spec_files": [
    "**/*[sS]pec.?(m)js"
  ],
  "helpers": [
    "helpers/**/*.?(m)js"
  ],
  "env": {
    "stopSpecOnExpectationFailure": false,
    "random": true
  }
}

Enfin, mettons à jour package.jsonpour configurer la commande testing :

{
  …
  "scripts": {
    "test": "jasmine"
  },
  …
}

Exécution de (pas) de tests

À ce stade, vous devriez avoir terminé toute la configuration nécessaire, et pas un seul test en place. Voyons si cela fonctionne comme prévu :

$ npm test

> how-to-unit-test@1.0.0 test
> jasmine

Randomized with seed 10285
Started


No specs found
Finished in 0.002 seconds
Incomplete: No specs found
Randomized with seed 10285 (jasmine --random=true --seed=10285)

Exemple d'essai

Ajoutons un test simple. Nous allons créer un nouveau fichier ./spec/pure-functions.spec.jsqui correspond à la convention Jasmine :

  • il se trouve dans le ./specdossier suivant ce qui est défini dans cette ligne de la configuration générée :"spec_dir": "spec",
  • il se termine par spec.js-un autre modèle de nommage établi dans"spec_files": ["**/*[sS]pec.?(m)js"

Code qui va à l'intérieur ./spec/pure-functions.spec.js:

import { greet } from "../pure-functions.js";

describe("greet", () => {
  it("should greet by name & surname", () => {
    expect(greet("Lorem", "Ipsum")).toEqual("Hello Lorem Ipsum!");
  });
});

Code:

  • import { greet } from "../pure-functions.js";-obtient la fonction à partir de notre code source. Cette ligne ne fonctionnerait pas comme prévu sans "type": "module",in package.json.
  • describe("", <callback>)-Enveloppe les tests associés pour de meilleurs messages d'erreur.
  • it("", <callback>)-un test individuel,
  • expect(<value>).<matcher>(<arguments>);-c'est ainsi que nous fixons les attentes à Jasmine. Vous pouvez trouver des matchers dans la documentation .

Courir!

Ce test en cours d'exécution :

$ npm run test

> how-to-unit-test@1.0.0 test
> jasmine

Randomized with seed 09863
Started
.


1 spec, 0 failures
Finished in 0.004 seconds
Randomized with seed 09863 (jasmine --random=true --seed=09863)

Code définitif

Vous pouvez trouver mon code final ici .

 Source : https://javascript.plainenglish.io/how-to-start-unit-testing-with-jasmine-ff55fa230fb5.

#jasmine #testing 

Comment Démarrer Les Tests Unitaires Avec Jasmine
Iara  Simões

Iara Simões

1661068920

Como Iniciar O Teste De Unidade Com Jasmine

Em meu artigo anterior , mostrei exemplos de pseudocódigo de funções puras de teste de unidade . Em resposta a esse artigo, recebi uma excelente pergunta - então, como faço para começar a testar meu código? Vamos dar uma olhada mais prática no mesmo caso simples para teste.

Obtenha a base de código

Preparei um repositório com o código de exemplo. O conteúdo principal é pure-functions.js:

export function greet(name, surname) {
  return `Hello ${name} ${surname}!`;
}

export function calculateDiscountedPrice(originalPrice, discount) {
  return originalPrice - originalPrice * discount;
}

export function power(base, exponent) {
  return base ** exponent;
}

Como você pode ver, o código é simples.

Peguei se você criar um novo pacote localmente

Se você deseja copiar o arquivo de código em vez de todo o repositório, há uma pegadinha. Você vai precisar:

  1. Gere um pacote com: npm initAssim, suas dependências de nós são instaladas na pasta atual.
  2. Mude o código para module , adicionando a package.json:
{
  …
  "type": "module",
  …
}

Você pode ver como é feito no meu repositório .

Instalar Jasmine

O código que vamos testar funcionará da mesma maneira no navegador ou no Node. Para simplificar, vamos testá-lo no Node. Primeiro, precisamos instalar o Jasmine. Para isso, vamos seguir a documentação oficial :

$ npm install --save-dev jasmine #1

$ npx jasmine init #2

Os comandos executam as seguintes funções:

  1. Instale o Jasmine como dependência de desenvolvimento
  2. Gere a configuração básica em spec/support/jasmine.json:
{
  "spec_dir": "spec",
  "spec_files": [
    "**/*[sS]pec.?(m)js"
  ],
  "helpers": [
    "helpers/**/*.?(m)js"
  ],
  "env": {
    "stopSpecOnExpectationFailure": false,
    "random": true
  }
}

Por fim, vamos atualizar package.jsonpara configurar o comando de teste:

{
  …
  "scripts": {
    "test": "jasmine"
  },
  …
}

Executando (não) testes

Neste ponto, você deve ter concluído toda a configuração necessária e não ter feito um único teste. Vamos ver se funciona como esperado:

$ npm test

> how-to-unit-test@1.0.0 test
> jasmine

Randomized with seed 10285
Started


No specs found
Finished in 0.002 seconds
Incomplete: No specs found
Randomized with seed 10285 (jasmine --random=true --seed=10285)

Exemplo de teste

Vamos adicionar um teste simples. Vamos criar um novo arquivo ./spec/pure-functions.spec.jsque corresponda à convenção Jasmine:

  • está dentro da ./specpasta seguindo o que está definido nesta linha da configuração gerada:"spec_dir": "spec",
  • termina com spec.js-outro padrão de nomenclatura estabelecido em"spec_files": ["**/*[sS]pec.?(m)js"

Código que vai dentro ./spec/pure-functions.spec.js:

import { greet } from "../pure-functions.js";

describe("greet", () => {
  it("should greet by name & surname", () => {
    expect(greet("Lorem", "Ipsum")).toEqual("Hello Lorem Ipsum!");
  });
});

Código:

  • import { greet } from "../pure-functions.js";-obtém a função do nosso código-fonte. Esta linha não funcionaria como esperado sem "type": "module",o package.json.
  • describe("", <callback>)- envolve testes relacionados para melhores mensagens de erro.
  • it("", <callback>)-um teste individual,
  • expect(<value>).<matcher>(<arguments>);-é como estabelecemos expectativas em Jasmine. Você pode encontrar correspondentes na documentação .

Corre!

Este teste em execução:

$ npm run test

> how-to-unit-test@1.0.0 test
> jasmine

Randomized with seed 09863
Started
.


1 spec, 0 failures
Finished in 0.004 seconds
Randomized with seed 09863 (jasmine --random=true --seed=09863)

Código final

Você pode encontrar meu código final aqui .

 Fonte: https://javascript.plainenglish.io/how-to-start-unit-testing-with-jasmine-ff55fa230fb5

#jasmine #testing 

Como Iniciar O Teste De Unidade Com Jasmine
Saul  Alaniz

Saul Alaniz

1661068800

Cómo iniciar Las Pruebas Unitarias Con Jasmine

En mi artículo anterior , mostré ejemplos de pseudocódigo de funciones puras de pruebas unitarias . En respuesta a ese artículo, recibí una excelente pregunta: entonces, ¿cómo empiezo a probar mi código? Echemos un vistazo más práctico al mismo caso simple de prueba.

Obtener la base de código

Preparé un repositorio con el código de ejemplo. El contenido principal es pure-functions.js:

export function greet(name, surname) {  return `Hello ${name} ${surname}!`;}export function calculateDiscountedPrice(originalPrice, discount) {  return originalPrice - originalPrice * discount;}export function power(base, exponent) {  return base ** exponent;}

Como puede ver, el código es simple.

Gotcha si crea un nuevo paquete localmente

Si desea copiar el archivo de código en lugar de todo el repositorio, entonces hay un problema. Necesitaras:

  1. Genere un paquete con: npm initEntonces, las dependencias de su nodo se instalan en la carpeta actual.
  2. Cambie el código para que sea módulo , agregando a package.json:
{  …  "type": "module",  …}

Puedes ver cómo se hace en mi repositorio .

instalar jazmín

El código que vamos a probar funcionará de la misma manera en el navegador o en Node. Para simplificar, probemos en Node. Primero, necesitamos instalar Jasmine. Para hacerlo, sigamos la documentación oficial :

$ npm install --save-dev jasmine #1$ npx jasmine init #2

Los comandos realizan las siguientes funciones:

  1. Instalar Jasmine como dependencia de desarrollo
  2. Genere la configuración básica en spec/support/jasmine.json:
{  "spec_dir": "spec",  "spec_files": [    "**/*[sS]pec.?(m)js"  ],  "helpers": [    "helpers/**/*.?(m)js"  ],  "env": {    "stopSpecOnExpectationFailure": false,    "random": true  }}

Por último, actualicemos package.jsonpara configurar el comando de prueba:

{  …  "scripts": {    "test": "jasmine"  },  …}

Ejecutar (ninguna) prueba

En este punto, debería haber completado toda la configuración necesaria y ni una sola prueba en su lugar. Veamos si funciona como se esperaba:

$ npm test> how-to-unit-test@1.0.0 test> jasmineRandomized with seed 10285StartedNo specs foundFinished in 0.002 secondsIncomplete: No specs foundRandomized with seed 10285 (jasmine --random=true --seed=10285)

Prueba de ejemplo

Agreguemos una prueba simple. Crearemos un nuevo archivo ./spec/pure-functions.spec.jsque coincida con la convención Jasmine:

  • está dentro de la ./speccarpeta, siguiendo lo establecido en esta línea de la configuración generada:"spec_dir": "spec",
  • termina con spec.js-otro patrón de nomenclatura establecido en"spec_files": ["**/*[sS]pec.?(m)js"

Código que va dentro ./spec/pure-functions.spec.js:

import { greet } from "../pure-functions.js";describe("greet", () => {  it("should greet by name & surname", () => {    expect(greet("Lorem", "Ipsum")).toEqual("Hello Lorem Ipsum!");  });});

Código:

  • import { greet } from "../pure-functions.js";-obtiene la función de nuestro código fuente. Esta línea no funcionaría como se esperaba "type": "module",sin package.json.
  • describe("", <callback>)-envuelve las pruebas relacionadas para obtener mejores mensajes de error.
  • it("", <callback>)-una prueba individual,
  • expect(<value>).<matcher>(<arguments>);-así es como establecemos expectativas en Jasmine. Puede encontrar emparejadores en la documentación .

¡Correr!

Esta prueba se ejecuta:

$ npm run test> how-to-unit-test@1.0.0 test> jasmineRandomized with seed 09863Started.1 spec, 0 failuresFinished in 0.004 secondsRandomized with seed 09863 (jasmine --random=true --seed=09863)

Código definitivo

Puedes encontrar mi código final aquí .

 Fuente: https://javascript.plainenglish.io/how-to-start-unit-testing-with-jasmine-ff55fa230fb5

#jasmine #testing 

Cómo iniciar Las Pruebas Unitarias Con Jasmine
Hoang  Kim

Hoang Kim

1661068800

Cách Bắt đầu Kiểm Tra đơn Vị Với Jasmine

Trong bài viết trước của tôi , tôi đã trình bày các ví dụ về mã giả của các chức năng thuần túy kiểm thử đơn vị . Để trả lời cho bài viết đó, tôi đã nhận được một câu hỏi tuyệt vời - vậy làm cách nào để tôi bắt đầu kiểm tra mã của mình sau đó? Chúng ta hãy xem xét thực tế hơn về cùng một trường hợp đơn giản để thử nghiệm.

Lấy cơ sở mã

Tôi đã chuẩn bị một kho lưu trữ với mã ví dụ. Nội dung chính là pure-functions.js:

export function greet(name, surname) {  return `Hello ${name} ${surname}!`;}export function calculateDiscountedPrice(originalPrice, discount) {  return originalPrice - originalPrice * discount;}export function power(base, exponent) {  return base ** exponent;}

Như bạn có thể thấy, mã rất đơn giản.

Gotcha nếu bạn tạo một gói mới cục bộ

Nếu bạn muốn sao chép tệp mã thay vì toàn bộ kho lưu trữ, thì có một gotcha. Bạn sẽ cần đến:

  1. Tạo một gói với: npm initVì vậy, các phần phụ thuộc vào nút của bạn đã được cài đặt trong thư mục hiện tại.
  2. Chuyển mã thành mô-đun , bằng cách thêm vào package.json:
{  …  "type": "module",  …}

Bạn có thể xem nó được thực hiện như thế nào trong repo của tôi .

Cài đặt Jasmine

Mã mà chúng tôi sắp kiểm tra sẽ hoạt động theo cùng một cách trên trình duyệt hoặc Node. Để đơn giản, hãy thử nghiệm nó trên Node. Đầu tiên, chúng ta cần cài đặt Jasmine. Để làm như vậy, hãy làm theo tài liệu chính thức :

$ npm install --save-dev jasmine #1$ npx jasmine init #2

Các lệnh thực hiện các chức năng sau:

  1. Cài đặt Jasmine làm phụ thuộc phát triển
  2. Tạo cấu hình cơ bản trong spec/support/jasmine.json:
{  "spec_dir": "spec",  "spec_files": [    "**/*[sS]pec.?(m)js"  ],  "helpers": [    "helpers/**/*.?(m)js"  ],  "env": {    "stopSpecOnExpectationFailure": false,    "random": true  }}

Cuối cùng, hãy cập nhật package.jsonđể cấu hình lệnh kiểm tra:

{  …  "scripts": {    "test": "jasmine"  },  …}

Đang chạy (không) kiểm tra

Tại thời điểm này, bạn đã hoàn thành tất cả các cấu hình cần thiết và không phải thực hiện một bài kiểm tra nào. Hãy xem nó có hoạt động như mong đợi không:

$ npm test> how-to-unit-test@1.0.0 test> jasmineRandomized with seed 10285StartedNo specs foundFinished in 0.002 secondsIncomplete: No specs foundRandomized with seed 10285 (jasmine --random=true --seed=10285)

Kiểm tra ví dụ

Hãy thêm một bài kiểm tra đơn giản. Chúng tôi sẽ tạo một tệp mới ./spec/pure-functions.spec.jsphù hợp với quy ước Jasmine:

  • nó nằm bên trong ./specthư mục theo sau những gì được đặt trong dòng này của cấu hình được tạo:"spec_dir": "spec",
  • nó kết thúc bằng spec.js-mẫu đặt tên khác được thiết lập trong"spec_files": ["**/*[sS]pec.?(m)js"

Mã bên trong ./spec/pure-functions.spec.js:

import { greet } from "../pure-functions.js";describe("greet", () => {  it("should greet by name & surname", () => {    expect(greet("Lorem", "Ipsum")).toEqual("Hello Lorem Ipsum!");  });});

Mã số:

  • import { greet } from "../pure-functions.js";-sử dụng chức năng từ mã nguồn của chúng tôi. Dòng này sẽ không hoạt động như mong đợi nếu không có "type": "module",trong package.json.
  • describe("", <callback>)-wraps các bài kiểm tra liên quan để có thông báo lỗi tốt hơn.
  • it("", <callback>)-một bài kiểm tra cá nhân,
  • expect(<value>).<matcher>(<arguments>);-đó là cách chúng tôi đặt kỳ vọng ở Jasmine. Bạn có thể tìm thấy các đối sánh trong tài liệu .

Chạy!

Thử nghiệm này đang chạy:

$ npm run test> how-to-unit-test@1.0.0 test> jasmineRandomized with seed 09863Started.1 spec, 0 failuresFinished in 0.004 secondsRandomized with seed 09863 (jasmine --random=true --seed=09863)

Mã cuối cùng

Bạn có thể tìm thấy mã cuối cùng của tôi ở đây .

 Nguồn: https://javascript.plainenglish.io/how-to-start-unit-testing-with-jasmine-ff55fa230fb5

#jasmine #testing 

Cách Bắt đầu Kiểm Tra đơn Vị Với Jasmine

How to Start Unit Testing with Jasmine

In my previous article, I showed pseudocode examples of unit testing pure functions. In response to that article, I got an excellent question-so how do I start testing my code then? Let’s take a more practical look at the same, simple case for testing.

Get the codebase

I prepared a repository with the example code. The main content is pure-functions.js:

 See more at: https://javascript.plainenglish.io/how-to-start-unit-testing-with-jasmine-ff55fa230fb5

#jasmine #testing 

How to Start Unit Testing with Jasmine
Lawrence  Lesch

Lawrence Lesch

1659647340

Suggested Best Practices When Writing Jasmine Unit Tests

Jasmine Style Guide

Purpose

The purpose of this style guide is to offer suggested best practices when writing Jasmine unit tests.

Contributing

This style guide ultimately represents the opinions of its contributors. If you disagree with anything, or wish to add more, please create an issue or submit a pull request. Our goal is to continuously improve the guide and build consensus around it.

Rules

  1. Speak Human
  2. Write Unit Tests
  3. Arrange-Act-Assert
  4. Don't Repeat Yourself
  5. this Is How We Do It
  6. Avoid the Alls
  7. Be describetive
  8. Write Minimum Passable Tests

Speak Human

Label your test suites (describe blocks) and specs (it blocks) in a way that clearly conveys the intention of each unit test. Note that the name of each test is the title of its it preceded by all its parent describe names. Favor assertive verbs and avoid ones like "should."

Why?

  • Test suite becomes documentation for your codebase (helpful for new team members and non-technical stakeholders)
  • Failure messages accurately depict what is broken
  • Forces good naming conventions in tested code

Bad:

// Output: "Array adds to the end"
describe('Array', function() {
  it('adds to the end', function() {
    var initialArray = [1];
    initialArray.push(2);
    expect(initialArray).toEqual([1, 2]);
  });
});

Better:

// Output: "Array.prototype .push(x) appends x to the end of the Array"
describe('Array.prototype', function() {
  describe('.push(x)', function() {
    it('appends x to the end of the Array', function() {
      var initialArray = [1];
      initialArray.push(2);
      expect(initialArray).toEqual([1, 2]);
    });
  });
});

Write Unit Tests

A unit test should test one thing. Confine your it blocks to a single assertion.

Why?

  • Single responsibility principle
  • A test can fail for only one reason

Bad:

describe('Array.prototype', function() {
  describe('.push(x)', function() {
    it('appends x to the end of the Array and returns it', function() {
      var initialArray = [1];
      expect(initialArray.push(2)).toBe(2);
      expect(initialArray).toEqual([1, 2]);
    });
  });
});

Better:

describe('Array.prototype', function() {
  describe('.push(x)', function() {
    it('appends x to the end of the Array', function() {
      var initialArray = [1];
      initialArray.push(2);
      expect(initialArray).toEqual([1, 2]);
    });

    it('returns x', function() {
      var initialArray = [1];
      expect(initialArray.push(2)).toBe(2);
    });
  });
});

Arrange-Act-Assert

Organize your code in a way that clearly conveys the 3 A's of each unit test. One way to accomplish this is by Arranging and Acting in before blocks and Asserting in it ones.

Why?

  • The AAA unit test pattern is well known and recommended
  • Improves unit test modularity and creates opportunities to DRY things up

Bad:

describe('Array.prototype', function() {
  describe('.push(x)', function() {
    it('appends x to the end of the Array', function() {
      var initialArray = [1];
      initialArray.push(2);
      expect(initialArray).toEqual([1, 2]);
    });
  });
});

Better:

describe('Array.prototype', function() {
  describe('.push(x)', function() {
    var initialArray;

    beforeEach(function() {
      initialArray = [1]; // Arrange

      initialArray.push(2); // Act
    });

    it('appends x to the end of the Array', function() {
      expect(initialArray).toEqual([1, 2]); // Assert
    });
  });
});

Don't Repeat Yourself

Use before/after blocks to DRY up repeated setup, teardown, and action code.

Why?

  • Keeps test suite more concise and readable
  • Changes only need to be made in one place
  • Unit tests are not exempt from coding best practices

Bad:

describe('Array.prototype', function() {
  describe('.push(x)', function() {
    it('appends x to the end of the Array', function() {
      var initialArray = [1];
      initialArray.push(2);
      expect(initialArray).toEqual([1, 2]);
    });

    it('returns x', function() {
      var initialArray = [1];
      expect(initialArray.push(2)).toBe(2);
    });
  });
});

Better:

describe('Array.prototype', function() {
  describe('.push(x)', function() {
    var initialArray,
        pushResult;

    beforeEach(function() {
      initialArray = [1];

      pushResult = initialArray.push(2);
    });

    it('appends x to the end of the Array', function() {
      expect(initialArray).toEqual([1, 2]);
    });

    it('returns x', function() {
      expect(pushResult).toBe(2);
    });
  });
});

this Is How We Do It

Use this to share variables between it and before/after blocks.

Why?

  • Declare and initialize variables on one line
  • Jasmine automatically cleans the this object between specs to avoid state leak

Bad:

describe('Array.prototype', function() {
  describe('.push(x)', function() {
    var initialArray,
        pushResult;

    beforeEach(function() {
      initialArray = [1];

      pushResult = initialArray.push(2);
    });

    it('appends x to the end of the Array', function() {
      expect(initialArray).toEqual([1, 2]);
    });

    it('returns x', function() {
      expect(pushResult).toBe(2);
    });
  });
});

Better:

describe('Array.prototype', function() {
  describe('.push(x)', function() {
    beforeEach(function() {
      this.initialArray = [1];

      this.pushResult = this.initialArray.push(2);
    });

    it('appends x to the end of the Array', function() {
      expect(this.initialArray).toEqual([1, 2]);
    });

    it('returns x', function() {
      expect(this.pushResult).toBe(2);
    });
  });
});

Avoid the Alls

Prefer beforeEach/afterEach blocks over beforeAll/afterAll ones. The latter are not reset between tests.

Why?

  • Avoids accidental state leak
  • Enforces test independence
  • Order of All block execution relative to Each ones is not always obvious

Bad:

describe('Array.prototype', function() {
  describe('.push(x)', function() {
    beforeAll(function() {
      this.initialArray = [1];
    });

    beforeEach(function() {
      this.pushResult = this.initialArray.push(2);
    });

    it('appends x to the end of the Array', function() {
      expect(this.initialArray).toEqual([1, 2]);
    });

    it('returns x', function() {
      expect(this.pushResult).toBe(2);
    });
  });
});

Better:

describe('Array.prototype', function() {
  describe('.push(x)', function() {
    beforeEach(function() {
      this.initialArray = [1];

      this.pushResult = this.initialArray.push(2);
    });

    it('appends x to the end of the Array', function() {
      expect(this.initialArray).toEqual([1, 2]);
    });

    it('returns x', function() {
      expect(this.pushResult).toBe(2);
    });
  });
});

Be describetive

Nest describe blocks liberally to create functional subsets.

Why?

  • Allows tests to build on each other from least to most specific
  • Creates tests that are easy to extend and/or refactor
  • Makes branch testing easier and less repetitive
  • Encapsulates tests based on their common denominator

Bad:

describe('Array.prototype', function() {
  describe('.push(x) on an empty Array', function() {
    beforeEach(function() {
      this.initialArray = [];

      this.initialArray.push(1);
    });

    it('appends x to the Array', function() {
      expect(this.initialArray).toEqual([1]);
    });
  });

  describe('.push(x) on a non-empty Array', function() {
    beforeEach(function() {
      this.initialArray = [1];

      this.initialArray.push(2);
    });

    it('appends x to the end of the Array', function() {
      expect(this.initialArray).toEqual([1, 2]);
    });
  });
});

Better:

describe('Array.prototype', function() {
  describe('.push(x)', function() {
    describe('on an empty Array', function() {
      beforeEach(function() {
        this.initialArray = [];

        this.initialArray.push(1);
      });

      it('appends x to the Array', function() {
        expect(this.initialArray).toEqual([1]);
      });
    });

    describe('on a non-empty Array', function() {
      beforeEach(function() {
        this.initialArray = [1];

        this.initialArray.push(2);
      });

      it('appends x to the end of the Array', function() {
        expect(this.initialArray).toEqual([1, 2]);
      });
    });
  });
});

Write Minimum Passable Tests

If appropriate, use Jasmine's built-in matchers (such as toContain, jasmine.any, jasmine.stringMatching, ...etc) to compare arguments and results. You can also create your own matcher via the asymmetricMatch function.

Why?

  • Tests become more resilient to future changes in the codebase
  • Closer to testing behavior over implementation

Bad:

describe('Array.prototype', function() {
  describe('.push(x)', function() {
    beforeEach(function() {
      this.initialArray = [];

      this.initialArray.push(1);
    });

    it('appends x to the Array', function() {
      expect(this.initialArray).toEqual([1]);
    });
  });
});

Better:

describe('Array.prototype', function() {
  describe('.push(x)', function() {
    beforeEach(function() {
      this.initialArray = [];

      this.initialArray.push(1);
    });

    it('appends x to the Array', function() {
      expect(this.initialArray).toContain(1);
    });
  });
});

Download Details: 

Author: CareMessagePlatform
Source Code: https://github.com/CareMessagePlatform/jasmine-styleguide 

#javascript #jasmine #style

Suggested Best Practices When Writing Jasmine Unit Tests
Tyree  Becker

Tyree Becker

1658228940

How to Add The Coverage Reports using Karma-Coverage Plugin & Istanbul

Add coverage Reports using karma-coverage plugin in the Karma application - Jasmine Testing. In this video we will see how to add the coverage reports using Karma-coverage plugin and Istanbul - Jasmine Testing.

GitHub: https://github.com/leelanarasimha

#testing #javascript #jasmine 

How to Add The Coverage Reports using Karma-Coverage Plugin & Istanbul
Tyree  Becker

Tyree Becker

1658138880

How Adding Chrome Headless Browser in The Karma Config File - Jasmine

Install Puppeteer for adding Chrome Headless browser in the karma config file - Jasmine Testing. In this video we will see how to install Puppeteer for adding the chrome headless browser for automating the Karma Testing - Jasmine Testing.

GitHub: https://github.com/leelanarasimha

#testing #javascript #jasmine 

How Adding Chrome Headless Browser in The Karma Config File - Jasmine
Tyree  Becker

Tyree Becker

1658045040

Create Karma Configuration File, karma.config.js - Jasmine Testing

Create Karma Configuration file, karma.config.js for running Tests in app - Jasmine Testing. In this video we will see how to create the Karma configuration file, karma.config.js file for running the jasmine tests - Jasmine Testing.

GitHub: https://github.com/leelanarasimha

#testing #javascript #jasmine 

Create Karma Configuration File, karma.config.js - Jasmine Testing
Tyree  Becker

Tyree Becker

1657965720

How to Install The Karma Runner and Jasmine - Jasmine Testing

Install the Karma Runner and Jasmine as dev dependencies in the application - Jasmine Testing. In this video we will see how to install the Karma Test Runner Tool and the Jasmine as the dev dependencies in the calculator application - Jasmine Testing.

GitHub: https://github.com/leelanarasimha

#testing #javascript #jasmine 

How to Install The Karma Runner and Jasmine - Jasmine Testing
Tyree  Becker

Tyree Becker

1657871760

Karma Test Runner: Automating Tests in Jasmine Testing Application

Understand Karma Test Runner Tool for automating tests in Jasmine Testing application. In this video we will see about the karma as a test runner tool for automating the tests in Jasmine Testing.

GitHub: https://github.com/leelanarasimha

#testing #javascript #jasmine 

Karma Test Runner: Automating Tests in Jasmine Testing Application
Tyree  Becker

Tyree Becker

1657792380

Initialize The NPM Package, Create package.json File In Calculator App

Initialize the npm package and create package.json file in calculator app - Jasmine Testing. In this video we will see how to initialize the npm package and create package.json file in the calculator file - Jasmine Testing.

GitHub: https://github.com/leelanarasimha

#testing #javascript #jasmine 

Initialize The NPM Package, Create package.json File In Calculator App
Tyree  Becker

Tyree Becker

1657698180

Ow to Test The JavaScript async and Await Calls - Jasmine Testing

Testing JavaScript async and await calls - Jasmine Testing. In this video we will see how to test the JavaScript async and await calls - Jasmine Testing.

GitHub: https://github.com/leelanarasimha

#testing #javascript #jasmine #async 

Ow to Test The JavaScript async and Await Calls - Jasmine Testing