-
Getting Started
a. install jest
npm install --save-dev jestb. edit
package.json{
"scripts": {
"test": "jest"
}
}c. write a test file named
sum.test.jstest('adds 1 + 2 to equal 3', () => {
expect(1+2).toBe(3);
});d. run the test from command line
npm test -- -
API - Expect Methods
a. Value
// methods used frequently
expect(n).toBe();
expect(n).not.toBe();
expect(n).toEqual();
expect(n).toStrictEqual();
expect(n).toBeNull();
expect(n).toBeDefined();
expect(n).toBeUndefined();
expect(n).toBeTruthy();
expect(n).toBeFalsy();b. Numbers
expect(value).toBeGreaterThan(3); expect(value).toBeGreaterThanOrEqual(3.5);
expect(value).toBeLessThan(5);
expect(value).toBeLessThanOrEqual(4.5);c. Arrays
expect(shoppingList).toContain('beer');d. Exceptions
expect(compileAndroidCode).toThrow();
expect(compileAndroidCode).toThrow(ConfigError);e. Promises
expect(fetchData()).resolves.toBe('peanut butter');
expect(fetchData()).rejects.toMatch('error');Complete method reference is here https://jestjs.io/docs/en/expect
-
Setup and Teardown
If you have some work you need to do repeatedly for many tests, you can use
beforeEachandafterEach.If you need to setup or teardown once, you can use
beforeAllandafterAll.beforeEach(() => {
initializeCityDatabase();
});
afterEach(() => {
clearCityDatabase();
});
beforeAll(() => {
return initializeCityDatabase();
});
afterAll(() => {
return clearCityDatabase();
}); -
Scoping - describe block
By default, the
beforeandafterblocks apply to every test in a file. You can also group tests together using adescribeblock. When they are inside adescribeblock, thebeforeandafterblocks only apply to the tests within thatdescribeblock.describe('matching cities to foods', () => {
beforeEach(() => {
return initializeFoodDatabase();
});
test('Vienna <3 sausage', () => {
expect(isValidCityFoodPair('Vienna', 'WienerSchnitzel')).toBe(true);
});
test('San Juan <3 plantains', () => {
expect(isValidCityFoodPair('San Juan', 'Mofongo')).toBe(true);
});
}); -
Test Express.js with Supertest - test HTTP request
First of all, you need to install
babel-cli,babel-preset-env,jest,supertestandsuperagent.Test GET
const request = require('supertest');
const app = require('../app');
describe('Test GET /', () => {
test('It should return 200 status code', () => {
return request(app).get('/').then(res => {
expect(res.statusCode).toBe(200);
});
});
});Test POST
describe('Test GET /', () => {
test('It should return some res', (done) => {
return request(app)
.post('/wechat?open_id=abc')
.type('xml')
.send('<xml>' +
'<ToUserName>testuser</ToUserName>' +
'<FromUserName>testuser</FromUserName>' +
'<CreateTime>1348831860</CreateTime>' +
'<MsgType>text</MsgType>' +
'<Content>testcontent</Content>' +
'<MsgId>1234567890</MsgId>' +
'</xml>');
})
.then(res => {
setTimeout(() => {
expect(res.text).toMatch('some res');
done();
}, 500);
});
});
});
}); -
Mock function
Mock functions make it easy to test the links between code by erasing the actual implementation of a function, capturing calls to the function (and the parameters passed in those calls), capturing instances of constructor functions when instantiated with
new, and allowing test-time configuration of return values.jest.fn([implementation])return a new, unused mock function.I used mock function to record all log strings in a string instead of printing it on command line. Below example is mocking
console.log.let log_output = "";
const storeLog = input => (log_output += input);
test('It should save all log strings in log_output', () => {
console.log = jest.fn(storeLog); // mock function
execute_some_func()
.then(() => {
expect(log_output).toMatch('Success');
});
}); -
Built-in code coverage reports
The
jestcommand line runner has a number of useful options. Below is one useful option coverage.--coverage: Indicates that test coverage information should be collected and reported in the output.We can easily create code coverage reports using
--coverage. No additional setup or libraries needed! Jest can collect code coverage information from entire projects, including untested files.
-
Reference
本文详细介绍使用 Jest 进行 JavaScript 测试的方法,包括安装配置、编写测试用例、使用 expect 断言方法、设置前后置操作、描述块的使用、HTTP 请求测试以及模拟函数的应用。同时提供代码覆盖率报告的生成方法。
1110

被折叠的 条评论
为什么被折叠?



