NPM jasmine-core Package
Jasmine-Core
Overview
Jasmine-Core is a simple framework for writing unit tests in JavaScript. It lets you write tests that self-document and become more readable and maintainable. Jasmine-Core is used for testing both synchronous and asynchronous code.
Installation
npm install --save-dev jasmine-core
Usage
To use Jasmine-Core, you first need to define the test suite and the test cases as shown below:
describe("A suite", function() {
it("contains spec with an expectation", function() {
expect(true).toBe(true);
});
});
describe: defines a test suite. A suite is a collection of related test cases.
it: defines a test case. A test case is a single test that verifies a specific behavior of the code being tested.
expect: asserts the expected outcome of the test.
Configuration Options
Jasmine-Core provides various configuration options to customize the testing environment. These options can be set before running the tests.
jasmine.DEFAULT_TIMEOUT_INTERVAL: Sets the default timeout interval for all asynchronous tests.
jasmine.DEFAULT_UPDATE_INTERVAL: Sets the default interval for updating the test runner UI.
jasmine.getEnv().addReporter: Adds a new reporter to the test runner.
jasmine.getEnv().configure: Configures the test runner with the provided options.
Best Practices
Here are some best practices for writing tests with Jasmine-Core:
- Keep tests independent: Each test case should be independent of other test cases.
- Use descriptive names: Use clear and concise names for test suites and test cases.
- Avoid nesting: Avoid nesting test suites and test cases too deeply.
- Use spies and mocks: Use spies and mocks to isolate the code being tested from its dependencies.
- Clean up after each test: Make sure to clean up any resources or state changes made during each test case.
Implementation Guide
To implement Jasmine-Core in your project, follow these steps:
- Create a new test file (e.g., spec.js)
- Include the Jasmine-Core library:
<script src="jasmine-core.js"></script>
- Define your test suites and test cases:
describe("A suite", function() {
it("contains spec with an expectation", function() {
expect(true).toBe(true);
});
});
- Run your tests using a test runner like Karma or Mocha:
karma start
Examples
Example 1: Testing a function
describe("A Calculator", function() {
it("can add two numbers", function() {
const calculator = new Calculator();
expect(calculator.add(1, 2)).toBe(3);
});
});
Example 2: Testing asynchronous code
describe("An asynchronous function", function() {
it("returns a value after 1 second", function(done) {
setTimeout(function() {
done();
}, 1000);
});
});