1661076240
前回の記事では、純粋関数の単体テストの疑似コード例を示しました。その記事への回答として、素晴らしい質問を受け取りました。では、コードのテストを開始するにはどうすればよいでしょうか? テストの同じ単純なケースをより実用的に見てみましょう。
コードベースを入手する
サンプルコードのリポジトリを用意しました。主な内容は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
したがって、ノードの依存関係は現在のフォルダーにインストールされます。package.json
に切り替えます。{
…
"type": "module",
…
}
私のレポでそれがどのように行われたかを見ることができます。
ジャスミンをインストール
テストするコードは、ブラウザまたはノードで同じように機能します。簡単にするために、ノードでテストしてみましょう。まず、ジャスミンをインストールする必要があります。そのためには、公式ドキュメントに従いましょう:
$ npm install --save-dev jasmine #1
$ npx jasmine init #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
-で確立された別の命名パターンで終わります"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
1661076240
在我之前的文章中,我展示了单元测试纯函数的伪代码示例。在回复那篇文章时,我得到了一个很好的问题——那么我该如何开始测试我的代码呢?让我们更实际地看一下相同的简单测试案例。
获取代码库
我准备了一个包含示例代码的存储库。主要内容是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;
}
如您所见,代码很简单。
如果你在本地创建一个新包,就会遇到问题
如果您想复制代码文件而不是整个存储库,那么有一个问题。您将需要:
npm init
因此,您的节点依赖项安装在当前文件夹中。package.json
:{
…
"type": "module",
…
}
你可以在我的 repo中看到它是如何完成的。
安装茉莉花
我们将要测试的代码将在浏览器或 Node 上以相同的方式工作。为简单起见,让我们在 Node.js 上进行测试。首先,我们需要安装 Jasmine。为此,让我们按照官方文档:
$ npm install --save-dev jasmine #1
$ npx jasmine init #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
1661072520
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:
npm init
Ainsi, vos dépendances de nœuds sont installées dans le dossier en cours.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 :
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.json
pour 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.js
qui correspond à la convention Jasmine :
./spec
dossier suivant ce qui est défini dans cette ligne de la configuration générée :"spec_dir": "spec",
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.
1661068920
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:
npm init
Assim, suas dependências de nós são instaladas na pasta atual.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:
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.json
para 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.js
que corresponda à convenção Jasmine:
./spec
pasta seguindo o que está definido nesta linha da configuração gerada:"spec_dir": "spec",
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
1661068800
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:
npm init
Entonces, las dependencias de su nodo se instalan en la carpeta actual.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:
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.json
para 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.js
que coincida con la convención Jasmine:
./spec
carpeta, siguiendo lo establecido en esta línea de la configuración generada:"spec_dir": "spec",
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
1661068800
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:
npm init
Vì 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.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:
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.js
phù hợp với quy ước Jasmine:
./spec
thư 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",
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
1661058300
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
1659647340
Jasmine Style Guide
The purpose of this style guide is to offer suggested best practices when writing Jasmine unit tests.
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.
this
Is How We Do ItAll
sdescribe
tiveLabel 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."
// 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]);
});
});
// 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]);
});
});
});
A unit test should test one thing. Confine your it
blocks to a single assertion.
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]);
});
});
});
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);
});
});
});
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.
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]);
});
});
});
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
});
});
});
Use before
/after
blocks to DRY up repeated setup, teardown, and action code.
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);
});
});
});
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 ItUse this
to share variables between it
and before
/after
blocks.
this
object between specs to avoid state leakdescribe('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);
});
});
});
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);
});
});
});
All
sPrefer beforeEach/afterEach
blocks over beforeAll/afterAll
ones. The latter are not reset between tests.
All
block execution relative to Each
ones is not always obviousdescribe('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);
});
});
});
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);
});
});
});
describe
tiveNest describe
blocks liberally to create functional subsets.
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]);
});
});
});
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]);
});
});
});
});
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.
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]);
});
});
});
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);
});
});
});
Author: CareMessagePlatform
Source Code: https://github.com/CareMessagePlatform/jasmine-styleguide
1658228940
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.
1658138880
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.
1658045040
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.
1657965720
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.
1657871760
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.
1657792380
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.
1657698180
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.