fullstack react 学习笔记 unit testing(1)jest基础
使用jest
语法:
expect().toBe():相当于===,不能用于比较对象
expect().toEqual():可以用于所有值的比较,包括对象。
describe('string',()=>{
it('string',()=>{expect().toBe()})
})
示例:
describe('My test suite', () => {
it('`true` should be `true`', () => {
expect(true).toBe(true);
});
it('`false` should be `false`', () => {
expect(false).toBe(false);
});
});
Modash.js:
// We write the Modash library in this file in the Unit Testing chapter
function truncate(string, length) {
if (string.length > length) {
return string.slice(0, length) + '...';
} else {
return string;
}
}
function capitalize(string) {
return (
string.charAt(0).toUpperCase() + string.slice(1).toLowerCase()
);
}
function camelCase(string) {
const words = string.split(/[\s|\-|_]+/);
return [
words[0].toLowerCase(),
...words.slice(1).map((w) => capitalize(w)),
].join('');
}
const Modash = {
truncate,
capitalize,
camelCase,
};
export default Modash;
Modash.test.js
// We write the tests for the Modash library in
// this file in the Unit Testing chapter
import Modash from './Modash';
describe('Modash', () => {
describe('`truncate()`', () => {
const string = 'there was one catch, and that was CATCH-22';
it('truncates a string', () => {
expect(
Modash.truncate(string, 19)
).toEqual('there was one catch...');
});
it('no-ops if <= length', () => {
expect(
Modash.truncate(string, string.length)
).toEqual(string);
});
});
describe('capitalize()', () => {
it('capitalizes first letter, lowercases rest', () => {
const string = 'there was one catch, and that was CATCH-22';
expect(
Modash.capitalize(string)
).toEqual(
'There was one catch, and that was catch-22'
);
});
});
describe('camelCase()', () => {
it('camelizes string with spaces', () => {
const string = 'customer responded at';
expect(
Modash.camelCase(string)
).toEqual('customerRespondedAt');
});
it('camelizes string with underscores', () => {
const string = 'customer_responded_at';
expect(
Modash.camelCase(string)
).toEqual('customerRespondedAt');
});
});
});
浙公网安备 33010602011771号