Share 7 professional-level JavaScript testing libraries to improve your work efficiency

ca4c5a48f65346d0cedac25b5cc1a16a.jpeg

Create an application that doesn't crash

025753ee0fe5a797df07015da60c5c75.png

In modern software development, writing and maintaining high-quality test cases has become an important part of our daily work. As one of the most popular programming languages ​​in the world, JavaScript has a large number of libraries and frameworks, which can help us better test.

In this article, I will introduce you to seven excellent JavaScript testing libraries, including Jest, Sinon, Detox, Cucumber, Stryker, TestDouble, and Mockttp. These libraries are excellent in their respective domains, such as unit testing, functional testing, mocking, integration testing, and mutation testing. Through the introduction of this article, I hope you can have a deeper understanding of these libraries and find a testing tool suitable for your project.

1、Jasmine

7c9663f58038aa56ea419ae1f9a0d813.jpeg

This is one of the top repositories with over 15500 stars on GitHub. This is a great resource if you want to do Behavior Driven Development testing in your projects. It doesn't depend on the browser, the DOM, or any JavaScript framework, so it's perfect for websites, Node.js projects, or anywhere JavaScript can run. You can check out this library by clicking here.

https://github.com/jasmine/jasmine

Example of use

Jasmine is a behavior-driven development (BDD) testing framework for JavaScript code. It doesn't require a DOM and it runs in any JavaScript-enabled environment, including Node.js and the browser.

First, you need to install Jasmine. In a Node.js environment, you can install it via npm (Node Package Manager):

npm install --save-dev jasmine

After installing Jasmine, you can create some test files in your project. These test files are often called "spec" files, and in these files you write your test cases. Here is a simple example:

// myFunction.spec.js
const myFunction = require('./myFunction.js');

describe("myFunction", function() {
  it("应该返回 'Hello, World!'", function() {
    expect(myFunction()).toEqual('Hello, World!');
  });
});

In the above code, the describe function defines a set of related tests, and the it function defines a single test. The expect function and the toEqual function together form a test assertion, which determines whether the return value of myFunction is Hello, World!.

Suppose we have the following function under test:

// myFunction.js
function myFunction() {
  return 'Hello, World!';
}

module.exports = myFunction;

When you want to run the tests, you can run the following command in the terminal:

npx jasmine myFunction.spec.js

If the myFunction function behaves as we expect (that is, returns Hello, World!), then the test will pass. If the function doesn't behave as we expect, the test will fail with a message describing why it failed.

The above is the basic introduction and examples of the Jasmine library. You can visit its GitHub page for more information and detailed documentation.

2、Otherwise

97310fa921cb6e358d0cf927bb11a225.jpeg

This is a standalone library for creating test doubles (recon, stubs and mocks) in JavaScript tests. It helps you write tests in isolation by providing tools to verify function calls, control behavior, and more. It has over 9000 stars on GitHub. You can check out this library by clicking here.

https://github.com/sinonjs/sinon

3、Detox

0333245423798aaa03f42d72c8de96f6.png

This is a great resource if you want to test your mobile app. The high speed of native mobile development requires us to adopt a continuous integration workflow, which means that our reliance on manual quality assurance needs to be greatly reduced. This library lets you test your mobile app by running it on a real device or emulator, interacting with it just like a real user would. It has over 10,000 stars on GitHub. You can check out this library by clicking here.

https://github.com/wix/Detox

Example of use

Detox is a library for end-to-end testing React Native and other native mobile apps. Unlike other libraries, Detox provides a way to automatically simulate real user behavior and test application performance on real devices or emulators.

First, you need to install Detox and its command-line tools in your project. In a Node.js environment, you can use npm (Node Package Manager) to install:

npm install detox --save-dev
npm install -g detox-cli

Then, you need to configure Detox in your project. In your package.json file, you need to add a new field called "detox":

"detox": {
  "configurations": {
    "ios.sim.debug": {
      "binaryPath": "ios/build/Build/Products/Debug-iphonesimulator/YourApp.app",
      "build": "xcodebuild -project ios/YourApp.xcodeproj -scheme YourApp -configuration Debug -sdk iphonesimulator -derivedDataPath ios/build",
      "type": "ios.simulator",
      "device": {
        "type": "iPhone 11"
      }
    }
  }
}

In the above configuration, we defined a test configuration named "ios.sim.debug". This configuration specifies where your application is built, the type of application, and which device you want to run the tests on.

Next, you can write some end-to-end test cases. These test cases will run your application on the device you specify and simulate the behavior of real users. Here is a simple example:

// e2e/firstTest.spec.js
describe('Example', () => {
  beforeEach(async () => {
    await device.reloadReactNative();
  });

  it('should have welcome screen', async () => {
    await expect(element(by.id('welcome'))).toBeVisible();
  });
});

In the above code, we first call device.reloadReactNative() to ensure that the application is in a new state when each test case starts. Then we use expect and toBeVisible to assert whether the welcome screen is visible.

When you want to run tests, you need to build your app first, then run the tests:

detox build --configuration ios.sim.debug
detox test --configuration ios.sim.debug

If your app behaves as we expect, the test will pass. If the app doesn't behave as we expect, the test will fail with a message describing why it failed.

The above is the basic introduction and examples of the Detox library. You can visit its GitHub page for more information and detailed documentation.

4、Cucumber

947c450783fb47d30b8ad1042628c470.jpeg

Cucumber is a tool for running automated tests written in a simple language. Because they're written in plain language, anyone on your team can read them. Because anyone can read it, you can use them to help improve communication, collaboration, and trust in your team. This is the JavaScript implementation of Cucumber. It has over 4500 stars on GitHub. You can check out this library by clicking here.

https://github.com/cucumber/cucumber-js

Example of use

Cucumber is a Behavior-Driven Development (BDD) tool that allows developers to describe the behavior of an application in concise, near-natural language text statements (such as English), which can then be converted into executable tests.

First, you need to install Cucumber in your project. In a Node.js environment, you can use npm (Node Package Manager) to install:

npm install --save-dev @cucumber/cucumber

Next, you need to create a feature file (usually ending in .feature). This file uses a language called Gherkin to describe the behavior of the application. For example, you might have a features file like this:

# myFeature.feature
Feature: Saying hello
  Scenario: User says hello
    Given the user has opened the application
    When the user says hello
    Then the application should reply with "Hello, User!"

Then, you need to create some step definitions (step definitions). Step definitions are functions written in JavaScript that will be used by Cucumber to execute each step in the function file. For example, you might have a step definition file like this:

// mySteps.js
const { Given, When, Then } = require('@cucumber/cucumber');

let appOpen = false;
let saidHello = false;

Given('the user has opened the application', function () {
  appOpen = true;
});

When('the user says hello', function () {
  if (appOpen) saidHello = true;
});

Then('the application should reply with "Hello, User!"', function () {
  if (appOpen && saidHello) {
    console.log('Hello, User!');
  }
});

Finally, you can run your function file through Cucumber CLI:

npx cucumber-js myFeature.feature

The above is the basic introduction and examples of the Cucumber library. You can visit its GitHub page for more information and detailed documentation.

5、Stryker

21bf3b3598c0092c106355bd8886fbd5.jpeg

Mutation testing makes changes to your code and then runs your unit tests against the changed code. Expect your unit tests to fail now. If they don't fail, it probably means your tests don't cover the code enough. As you guessed, this library will help you with mutation testing in your projects. It has over 2000 stars on GitHub. You can check out this library by clicking here.

https://github.com/stryker-mutator/stryker-js

Example of use

Stryker is a mutation testing framework that can help you improve the quality of your unit tests. Mutation testing works by making small modifications to your code (called "mutations") and then running your unit tests to see which modifications were not caught by the tests, which can help reveal blind spots in code coverage.

First, you need to install Stryker and the plugins it needs in your project. In a Node.js environment, you can use npm (Node Package Manager) to install:

npm install --save-dev @stryker-mutator/core @stryker-mutator/mocha-runner @stryker-mutator/javascript-mutator

In the example above, we installed Stryker's core library, a runner for running Mocha tests, and JavaScript mutators.

Then, you need to create a Stryker configuration file. This file is usually named stryker.conf.js and should be located in the root directory of the project. In this file you define how Stryker should run your tests and create mutations.

// stryker.conf.js
module.exports = function(config){
  config.set({
    mutator: "javascript",
    packageManager: "npm",
    reporters: ["clear-text", "progress"],
    testRunner: "mocha",
    transpilers: [],
    coverageAnalysis: "off",
    mutate: ["src/**/*.js"],
  });
};

In the above code, we tell Stryker to use the JavaScript mutator, npm as the package manager, and Mocha as the test runner. We also tell Stryker which files to mutate.

Now, you can run Stryker to perform mutation testing:

npx stryker run

Stryker generates a report showing whether each mutation is covered by tests. If your unit tests are not catching a certain mutation, then you may need to add or improve your tests.

The above is the basic introduction and examples of the Stryker library. You can visit its GitHub page for more information and detailed documentation.

6、TestDouble

135a25825e7f7562ae5df0849a7d608c.jpeg

Are you writing JavaScript tests and looking for a mocking library to mock the real thing for you? This is a well-designed test double library with its own unique insights. The library is designed to work with Node.js and browser interpreters. It's also test framework agnostic, so you can drop it into codebases that use Jasmine, Mocha, Tape, Jest, or our own teenytest. It has over 1000 stars on GitHub. You can check out this library by clicking here.

https://github.com/testdouble/testdouble.js

Example of use

TestDouble.js is a library for creating test doubles in JavaScript. It's designed to allow you to easily mock or fake dependencies in your unit tests, allowing you to better isolate and control your test environment.

First, you need to install TestDouble in your project. In a Node.js environment, you can use npm (Node Package Manager) to install:

npm install --save-dev testdouble

Next, you can use TestDouble in your unit tests. For example, you can use td.function() to create a mock function:

const td = require('testdouble');

// 创建一个模拟函数
const mockFunction = td.function();

// 使模拟函数在调用时返回特定的值
td.when(mockFunction('hello')).thenReturn('world');

// 现在,当你调用 mockFunction('hello') 时,它将返回 'world'
console.log(mockFunction('hello'));  // 输出: 'world'

You can also use TestDouble to mock objects, for example use td.object() to create a mock object:

const td = require('testdouble');

// 创建一个模拟对象
const mockObject = td.object(['method1', 'method2']);

// 使模拟对象的方法在调用时返回特定的值
td.when(mockObject.method1()).thenReturn('hello');

// 现在,当你调用 mockObject.method1() 时,它将返回 'hello'
console.log(mockObject.method1());  // 输出: 'hello'

TestDouble.js also provides many other features for creating and managing test doubles, such as verifying that functions are called, replacing modules, etc. The above is the basic introduction and examples of the TestDouble library, you can visit its GitHub page for more information and detailed documentation.

7、Mockttp

c662ceabdf2366f384ccea87b6181266.jpeg

HTTP testing is the most common and best supported use case. This library enables you to intercept, transform or test HTTP requests and responses in JavaScript quickly and reliably anywhere. You can use this library in your integration tests, as part of your test suite to intercept real requests, or you can use it to build custom HTTP proxies that capture, inspect and/or override in any way you like HTTP. You can check out this library by clicking here.

https://github.com/httptoolkit/mockttp

Example of use

Mockttp is a powerful library that allows you to intercept, inspect and modify HTTP requests and responses in JavaScript. This is very useful for integration testing and debugging HTTP communication.

First, you need to install Mockttp in your project. In a Node.js environment, you can use npm (Node Package Manager) to install:

npm install --save-dev mockttp

Next, we will introduce some basic usage methods:

// 引入需要的库
const superagent = require("superagent");
const mockServer = require("mockttp").getLocal();

// 在测试开始前启动Mock服务器,并在测试结束后关闭服务器
beforeEach(() => mockServer.start(8080));
afterEach(() => mockServer.stop());

// 模拟请求,并对结果进行断言
it("lets you mock requests, and assert on the results", async () => {
    // 模拟你的端点
    await mockServer.forGet("/mocked-path").thenReply(200, "A mocked response");

    // 发送一个请求
    const response = await superagent.get("http://localhost:8080/mocked-path");

    // 对结果进行断言
    expect(response.text).to.equal("A mocked response");
});

The above code creates a Mock server and sets up a simulated GET request. We then send an actual GET request and assert that the returned response text is equal to the mock response we set.

Mockttp also provides more advanced features, such as:

  • No need to specify ports, allowing parallel testing

  • Verify the request details received by the mock server

  • Proxy requests to any other host

Here are some more advanced examples:

const superagent = require("superagent");
require('superagent-proxy')(superagent);
const mockServer = require("mockttp").getLocal();

describe("Mockttp", () => {
    beforeEach(() => mockServer.start());
    afterEach(() => mockServer.stop());

    // 不指定端口,允许并行测试
    it("lets you mock without specifying a port, allowing parallel testing", async () => {
        await mockServer.forGet("/mocked-endpoint").thenReply(200, "Tip top testing");

        let response = await superagent.get(mockServer.urlFor("/mocked-endpoint"));

        expect(response.text).to.equal("Tip top testing");
    });

    // 验证mock服务器接收的请求详情
    it("lets you verify the request details the mockttp server receives", async () => {
        const endpointMock = await mockServer.forGet("/mocked-endpoint").thenReply(200, "hmm?");

        await superagent.get(mockServer.urlFor("/mocked-endpoint"));

        const requests = await endpointMock.getSeenRequests();
        expect(requests.length).to.equal(1);
        expect(requests[0].url).to.equal(`http://localhost:${mockServer.port}/mocked-endpoint`);
    });

    // 代理请求到任何其他主机
    it("lets you proxy requests made to any other hosts", async () => {
        await mockServer.forGet("http://google.com").thenReply(200, "I can't believe it's not google!");

        let response = await superagent.get("http://google.com").proxy(mockServer.url);

        expect(response.text).to.equal("I can't believe it's not google!");
    });
});

These examples use Mocha, Chai, and Superagent, but these are not required: Mockttp can be used with any testing tool that can handle promises, and can mock requests from any library, tool, or device.

end

In this article, we learned about seven JavaScript testing libraries: Jest, Sinon, Detox, Cucumber, Stryker, TestDouble, and Mockttp. Each library has its unique functions and features, which can help us write and manage test cases more efficiently and ensure the quality and stability of the code.

Whether you are a beginner or an experienced developer, these libraries will be powerful tools in your development process. I hope that through the introduction of this article, you can learn more about these libraries and find the most suitable tool for you.

Before ending this article, I would like to say that testing is an integral part of software development, and choosing and mastering appropriate testing tools can make our work easier. Finally, I hope this article can help you in your development work. If you have any questions or suggestions, please leave a message in the comment area. Thanks for reading and see you next time.

Due to the limited space of the article, today’s content will be shared here. At the end of the article, I would like to remind you that the creation of articles is not easy. If you like my sharing, please don’t forget to like and forward it, so that more people in need See. At the same time, if you want to gain more knowledge of front-end technology, welcome to follow me, your support will be the biggest motivation for me to share. I will continue to output more content, so stay tuned.

Guess you like

Origin blog.csdn.net/Ed7zgeE9X/article/details/131928785