Giter Site home page Giter Site logo

canechair.snippets's Introduction

[Simon's CaneChair] Snippets of Full-Stack Javascript. (for VS Code)

(It's time to sit down and enjoy the rocking...)

Visual Studio Marketplace Version Visual Studio Marketplace Downloads GitHub last commit GitHub commit activity the past week, 4 weeks, year GitHub issues GitHub closed issues


Snippets for Javascript Full-Stack Development using "VS Code", include:React, ReactNative, Vanilla JavaScript, Express, NodeJs, Jest, AWS, and more...

🚀(Keyboard shortcut works while entered enough characters to disambiguate the term, no fully input needed.)

(All snippets start with "cc" for convinence, stands for "CaneChair")


Get the extension here: VS Marketplace - CaneChairSnippets

GitHub: https://github.com/simon8029/CaneChair.Snippets.io

ReactJS (Javascript):

Snippet Name Keyboard Shortcut
ReactJS : Middleware : NewMiddleware ccReactJS_Middleware_NewMiddleware
ReactJS : JS : Component : Class ccReactJS_JS_Component_Class
ReactJS : JS : Component : Hooks ccReactJS_JS_Component_Hooks
ReactJS : JS : Component : Container ccReactJS_JS_Component_Container
ReactJS : JS : NewAction ccReactJS_JS_NewAction
ReactJS : JS : RootIndexFile ccReactJS_JS_RootIndexFile
ReactJS : JS : Store ccReactJS_JS_Store
ReactJS : JS : RootReducer ccReactJS_JS_RootReducer
ReactJS : JS : NewReducer ccReactJS_JS_NewReducer
ReactJS : JS : ActionTypes ccReactJS_JS_ActionTypes
ReactJS : JS : NewRoute ccReactJS_JS_NewRoute
ReactJS : Duck : NewDuck ccReactJS_Duck_NewDuck

ReactJS Elements:

Snippet Name Keyboard Shortcut
ReactJS : Element : Div ccReactJS_Element_Div
ReactJS : Element : Nav ccReactJS_Element_Nav
ReactJS : Element : Section ccReactJS_Element_Section
ReactJS : Element : Span ccReactJS_Element_Span
ReactJS : Element : A ccReactJS_Element_A
ReactJS : Element : Image ccReactJS_Element_Image
ReactJS : Element : Article ccReactJS_Element_Article
ReactJS : Element : Label ccReactJS_Element_Label
ReactJS : Element : Icon ccReactJS_Element_Icon
ReactJS : Element : Form ccReactJS_Element_Form
ReactJS : Element : Link ccReactJS_Element_Link
ReactJS : Element : Input ccReactJS_Element_Input
ReactJS : Element : Button ccReactJS_Element_Button
ReactJS : Element : H1 ccReactJS_Element_H1
ReactJS : Element : H2 ccReactJS_Element_H2
ReactJS : Element : H3 ccReactJS_Element_H3
ReactJS : Element : H4 ccReactJS_Element_H4
ReactJS : Element : H5 ccReactJS_Element_H5
ReactJS : Element : Ul ccReactJS_Element_Ul
ReactJS : Element : Li ccReactJS_Element_Li
ReactJS : Element : Paragraph ccReactJS_Element_P

Vanilla JavaScript

Snippet Name Keyboard Shortcut
Common : IIFE ccCommon_IIFE
Common : PrintToConsole cclog
Common : PrintToConsole : Group cclog_group
Common : Import : Module ccCommon_Import_Module
Common : Class : Constructor ccCommon_Class_Constructor
Common : Function : ArrowFunction ccCommon_Function_ArrowFunction
Common : Function : If ccCommon_Function_If
Common : Function : Switch ccCommon_Function_Switch
Common : Object : Assign ccCommon_Object_Assign
Common : Array : Map ccCommon_Array_Map
Common : Array : Find ccCommon_Array_Find
Common : Array : FindIndex ccCommon_Array_FindIndex
Common : Array : Filter ccCommon_Array_Filter
Common : Array : ForEach ccCommon_Array_ForEach

ReactNative:

Snippet Name Keyboard Shortcut
ReactNative : Component : Container ccReactNative_Component_Container
ReactNative : Component : Functional ccReactNative_Component_Functional
ReactNative : Element : View ccReactNative_Element_View
ReactNative : Element : ScrollView ccReactNative_Element_ScrollView
ReactNative : Element : Text ccReactNative_Element_Text
ReactNative : Element : TextInput ccReactNative_Element_TextInput
ReactNative : Element : ListView ccReactNative_Element_ListView
ReactNative : Element : Button ccReactNative_Element_Button
ReactNative : Element : Slider ccReactNative_Element_Slider
ReactNative : Element : Switch ccReactNative_Element_Switch
ReactNative : Element : Picker ccReactNative_Element_Picker
ReactNative : Element : DatePicker ccReactNative_Element_DatePicker

Test : Jest

Snippet Name Keyboard Shortcut
Test : Jest : InitTestFile : ReactJS ccTest_Jest_InitTestFile_ReactJS
Test : Jest : InitTestFile : VueJS ccTest_Jest_InitTestFile_VueJS
Test : Jest : Describe ccTest_Jest_Describe
Test : Jest : BeforeAll ccTest_Jest_BeforeAll
Test : Jest : BeforeEach ccTest_Jest_BeforeEach
Test : Jest : AfterAll ccTest_Jest_AfterAll
Test : Jest : AfterEach ccTest_Jest_AfterEach
Test : Jest : It ccTest_Jest_It
Test : Jest : ItAsync ccTest_Jest_ItAsync
Test : Jest : Expect : ToMatchSnapshot ccTest_Jest_Expect_ToMatchSnapshot
Test : Jest : Expect : ToBe ccTest_Jest_Expect_ToBe
Test : Jest : Expect : ToEqual ccTest_Jest_Expect_ToEqual
Test : Jest : Expect : ToBeCalledWith ccTest_Jest_Expect_ToBeCalledWith
Test : Jest : Expect : ToHaveBeenCalledWith ccTest_Jest_Expect_ToHaveBeenCalledWith
Test : Jest : Expect : ToHaveBeenCalled ccTest_Jest_Expect_ToHaveBeenCalled
Test : Jest : Expect : ToBeCalled ccTest_Jest_Expect_ToBeCalled
Test : Jest : Expect : ToHaveBeenCalledTimes ccTest_Jest_Expect_ToHaveBeenCalledTimes
Test : Jest : Expect : LastCalledWith ccTest_Jest_Expect_LastCalledWith
Test : Jest : Expect : ToBeCloseTo ccTest_Jest_Expect_ToBeCloseTo
Test : Jest : Expect : ToBeDefined ccTest_Jest_Expect_ToBeDefined
Test : Jest : Expect : ToBeFalsy ccTest_Jest_Expect_ToBeFalsy
Test : Jest : Expect : ToBeGreaterThan ccTest_Jest_Expect_ToBeGreaterThan
Test : Jest : Expect : ToBeGreaterThanOrEqual ccTest_Jest_Expect_ToBeGreaterThanOrEqual
Test : Jest : Expect : ToBeLessThan ccTest_Jest_Expect_ToBeLessThan
Test : Jest : Expect : ToBeLessThanOrEqual ccTest_Jest_Expect_ToBeLessThanOrEqual
Test : Jest : Expect : ToBeInstanceOf ccTest_Jest_Expect_ToBeInstanceOf
Test : Jest : Expect : ToBeNull ccTest_Jest_Expect_ToBeNull
Test : Jest : Expect : ToBeTruthy ccTest_Jest_Expect_ToBeTruthy
Test : Jest : Expect : ToBeUndefined ccTest_Jest_Expect_ToBeUndefined
Test : Jest : Expect : ToContain ccTest_Jest_Expect_ToContain
Test : Jest : Expect : ToContainEqual ccTest_Jest_Expect_ToContainEqual
Test : Jest : Expect : ToHaveLength ccTest_Jest_Expect_ToHaveLength
Test : Jest : Expect : ToMatch ccTest_Jest_Expect_ToMatch
Test : Jest : Expect : ToMatchObject ccTest_Jest_Expect_ToMatchObject
Test : Jest : Expect : ToHaveProperty ccTest_Jest_Expect_ToHaveProperty
Test : Jest : Expect : ToThrow ccTest_Jest_Expect_ToThrow
Test : Jest : Expect : ToThrowError ccTest_Jest_Expect_ToThrowError
Test : Jest : Expect : ToThrowErrorMatchingSnapshot ccTest_Jest_Expect_ToThrowErrorMatchingSnapshot
Test : Chai : Express : Module ccTest_Chai_Express_Module

Test : Chai

Snippet Name Keyboard Shortcut
Test : Chai : Express : Module ccTest_Chai_Express_Module
Test : Chai : Express : Middleware ccTest_Chai_Express_Middleware
Test : Chai : Express : Service ccTest_Chai_Express_Service
Test : Chai : Express : Controller ccTest_Chai_Express_Controller
Test : Chai : MongoDB : Module ccTest_Chai_MongoDB_Module
Test : Chai : MongoDB : Util ccTest_Chai_MongoDB_Util
Test : Chai : Fixture cc_Test_Chai_Fixture

Express :

Snippet Name Keyboard Shortcut
Express : Controller ccExpress_Controller
Express : MiddleWare ccExpress_MiddleWare
Express : Service ccExpress_Service
Express : Routes : Module : Exports : Function ccExpress_Routes_Module_Exports_Function
Express : Routes : SimpleAppRoute ccExpress_Routes_SimpleAppRoute
Express : Routes : Get ccExpress_Routes_Get
Express : Response : Status : 200 : Send ccExpress_Response_Status_200_Send
Express : Response : Status : 401 : Send ccExpress_Response_Status_401_Send
Express : Response : Status : 404 : Send ccExpress_Response_Status_404_Send
Express : Response : Status : 500 : Send ccExpress_Response_Status_500_Send

Mongo

Snippet Name Keyboard Shortcut
MongoDB : Module ccMongoose_Module
MongoDB : Model ccMongoose_Model
MongoDB : Config ccMongoose_Config

D3JS

Snippet Name Keyboard Shortcut
D3JS : dimensions ccD3_dimensions
D3JS : wrapper ccD3_wrapper
D3JS : bounds ccD3_bounds
D3JS : xScale : Linear ccD3_xScale_linear
D3JS : yScale : Linear ccD3_yScale_linear
D3JS : Axis ccD3_axis

GraphQL

Snippet Name Keyboard Shortcut
GraphQL : Client : Class cc_graphQL_client_class
GraphQL : Client : IndexJS cc_graphQL_client_indexJs
GraphQL : Server : appJS cc_graphQL_server_appJs
GraphQL : Server : TypeDefs : DefaultSchema cc_graphQL_server_typeDefs_defaultSchema
GraphQL : Server : TypeDefs : indexJs cc_graphQL_server_typeDefs_indexJs
GraphQL : Server : TypeDefs : Schema cc_graphQL_server_typeDefs_schema
GraphQL : Server : Resolvers : indexJs cc_graphQL_server_resolvers_indexJs
GraphQL : Server : Resolvers cc_graphQL_server_resolvers
GraphQL : Server : Model : IndexJS cc_graphQL_server_model_indexJs
GraphQL : Server : Model cc_graphQL_server_model
GraphQL : Server : Database cc_graphQL_server_database
GraphQL : Server : DummyData cc_graphQL_server_dummyData

canechair.snippets's People

Contributors

lrse1 avatar simon8029 avatar

Stargazers

 avatar  avatar

Watchers

 avatar

canechair.snippets's Issues

Add Jest : Expect : ToHaveBeenLastCalledWith

.toHaveBeenLastCalledWith(arg1, arg2, ...) #
Also under the alias: .lastCalledWith(arg1, arg2, ...)

If you have a mock function, you can use .toHaveBeenLastCalledWith to test what arguments it was last called with. For example, let's say you have a applyToAllFlavors(f) function that applies f to a bunch of flavors, and you want to ensure that when you call it, the last flavor it operates on is 'mango'. You can write:

test('applying to all flavors does mango last', () => {
  const drink = jest.fn();
  applyToAllFlavors(drink);
  expect(drink).toHaveBeenLastCalledWith('mango');
});

Add Jest : AfterEach

Runs a function after each one of the tests in this file completes. If the function returns a promise or is a generator, Jest waits for that promise to resolve before continuing.

Optionally, you can provide a timeout (in milliseconds) for specifying how long to wait before aborting. Note: The default timeout is 5 seconds.

This is often useful if you want to clean up some temporary state that is created by each test.

For example:

const globalDatabase = makeGlobalDatabase();

function cleanUpDatabase(db) {
  db.cleanUp();
}

afterEach(() => {
  cleanUpDatabase(globalDatabase);
});

test('can find things', () => {
  return globalDatabase.find('thing', {}, results => {
    expect(results.length).toBeGreaterThan(0);
  });
});

test('can insert a thing', () => {
  return globalDatabase.insert('thing', makeThing(), response => {
    expect(response.success).toBeTruthy();
  });
});

Here the afterEach ensures that cleanUpDatabase is called after each test runs.

If afterEach is inside a describe block, it only runs after the tests that are inside this describe block.

If you want to run some cleanup just once, after all of the tests run, use afterAll instead.

Add Jest : AfterAll

Runs a function after all the tests in this file have completed. If the function returns a promise or is a generator, Jest waits for that promise to resolve before continuing.

Optionally, you can provide a timeout (in milliseconds) for specifying how long to wait before aborting. Note: The default timeout is 5 seconds.

This is often useful if you want to clean up some global setup state that is shared across tests.

For example:

const globalDatabase = makeGlobalDatabase();

function cleanUpDatabase(db) {
  db.cleanUp();
}

afterAll(() => {
  cleanUpDatabase(globalDatabase);
});

test('can find things', () => {
  return globalDatabase.find('thing', {}, results => {
    expect(results.length).toBeGreaterThan(0);
  });
});

test('can insert a thing', () => {
  return globalDatabase.insert('thing', makeThing(), response => {
    expect(response.success).toBeTruthy();
  });
});

Here the afterAll ensures that cleanUpDatabase is called after all tests run.

If afterAll is inside a describe block, it runs at the end of the describe block.

If you want to run some cleanup after every test instead of after all tests, use afterEach instead.

Add Jest : Expect : ToBeInstanceOf

.toBeInstanceOf(Class) #
Use .toBeInstanceOf(Class) to check that an object is an instance of a class. This matcher uses instanceof underneath.

class A {}

expect(new A()).toBeInstanceOf(A);
expect(() => {}).toBeInstanceOf(Function);
expect(new A()).toBeInstanceOf(Function); // throws

Add Jest : Expect : ToMatchObject

.toMatchObject(object) #
Use .toMatchObject to check that a JavaScript object matches a subset of the properties of an object. It will match received objects with properties that are not in the expected object.

You can also pass an array of objects, in which case the method will return true only if each object in the received array matches (in the toMatchObject sense described above) the corresponding object in the expected array. This is useful if you want to check that two arrays match in their number of elements, as opposed to arrayContaining, which allows for extra elements in the received array.

You can match properties against values or against matchers.

const houseForSale = {
  bath: true,
  bedrooms: 4,
  kitchen: {
    amenities: ['oven', 'stove', 'washer'],
    area: 20,
    wallColor: 'white',
  },
};
const desiredHouse = {
  bath: true,
  kitchen: {
    amenities: ['oven', 'stove', 'washer'],
    wallColor: expect.stringMatching(/white|yellow/),
  },
};

test('the house has my desired features', () => {
  expect(houseForSale).toMatchObject(desiredHouse);
});
describe('toMatchObject applied to arrays arrays', () => {
  test('the number of elements must match exactly', () => {
    expect([{foo: 'bar'}, {baz: 1}]).toMatchObject([{foo: 'bar'}, {baz: 1}]);
  });

  // .arrayContaining "matches a received array which contains elements that
  // are *not* in the expected array"
  test('.toMatchObject does not allow extra elements', () => {
    expect([{foo: 'bar'}, {baz: 1}]).toMatchObject([{foo: 'bar'}]);
  });

  test('.toMatchObject is called for each elements, so extra object properties are okay', () => {
    expect([{foo: 'bar'}, {baz: 1, extra: 'quux'}]).toMatchObject([
      {foo: 'bar'},
      {baz: 1},
    ]);
  });
});

create Mongoose_Model_NewModel - mongoose

const mongoose = require('mongoose'),
Schema = mongoose.Schema,
ProfessionSchema = new Schema({
ProfessionName: {
type: String,
default: '',
required: 'ProfessionName cannot be empty'
}
});

mongoose.model('Profession', ProfessionSchema);

Add Jest : Expect : ToHaveBeenCalledTimes

Use .toHaveBeenCalledTimes to ensure that a mock function got called exact number of times.

For example, let's say you have a drinkEach(drink, Array) function that takes a drink function and applies it to array of passed beverages. You might want to check that drink function was called exact number of times. You can do that with this test suite:

test('drinkEach drinks each drink', () => {
  const drink = jest.fn();
  drinkEach(drink, ['lemon', 'octopus']);
  expect(drink).toHaveBeenCalledTimes(2);
});

Add Jest : Expect : ToContain

.toContain(item) #
Use .toContain when you want to check that an item is in an array. For testing the items in the array, this uses ===, a strict equality check. .toContain can also check whether a string is a substring of another string.

For example, if getAllFlavors() returns an array of flavors and you want to be sure that lime is in there, you can write:

test('the flavor list contains lime', () => {
  expect(getAllFlavors()).toContain('lime');
});

Add Jest : Expect : ToBeUndefined

.toBeUndefined() #
Use .toBeUndefined to check that a variable is undefined. For example, if you want to check that a function bestDrinkForFlavor(flavor) returns undefined for the 'octopus' flavor, because there is no good octopus-flavored drink:

test('the best drink for octopus flavor is undefined', () => {
  expect(bestDrinkForFlavor('octopus')).toBeUndefined();
});

You could write expect(bestDrinkForFlavor('octopus')).toBe(undefined), but it's better practice to avoid referring to undefined directly in your code.

Add Jest : Expect : ToBeNull

.toBeNull() #
.toBeNull() is the same as .toBe(null) but the error messages are a bit nicer. So use .toBeNull() when you want to check that something is null.

function bloop() {
  return null;
}

test('bloop returns null', () => {
  expect(bloop()).toBeNull();
});

Add Jest : Expect : ToHaveBeenCalledWith

.toHaveBeenCalledWith(arg1, arg2, ...) #
Also under the alias: .toBeCalledWith()

Use .toHaveBeenCalledWith to ensure that a mock function was called with specific arguments.

For example, let's say that you can register a beverage with a register function, and applyToAll(f) should apply the function f to all registered beverages. To make sure this works, you could write:

test('registration applies correctly to orange La Croix', () => {
  const beverage = new LaCroix('orange');
  register(beverage);
  const f = jest.fn();
  applyToAll(f);
  expect(f).toHaveBeenCalledWith(beverage);
});

Add Jest : Expect : ToBeFalsy

.toBeFalsy() #
Use .toBeFalsy when you don't care what a value is, you just want to ensure a value is false in a boolean context. For example, let's say you have some application code that looks like:

drinkSomeLaCroix();
if (!getErrors()) {
  drinkMoreLaCroix();
}

You may not care what getErrors returns, specifically - it might return false, null, or 0, and your code would still work. So if you want to test there are no errors after drinking some La Croix, you could write:

test('drinking La Croix does not lead to errors', () => {
  drinkSomeLaCroix();
  expect(getErrors()).toBeFalsy();
});

In JavaScript, there are six falsy values: false, 0, '', null, undefined, and NaN. Everything else is truthy.

Add Jest : Expect : ToContainEqual

.toContainEqual(item) #
Use .toContainEqual when you want to check that an item with a specific structure and values is contained in an array. For testing the items in the array, this matcher recursively checks the equality of all fields, rather than checking for object identity.

describe('my beverage', () => {
  test('is delicious and not sour', () => {
    const myBeverage = {delicious: true, sour: false};
    expect(myBeverages()).toContainEqual(myBeverage);
  });
});

Add Jest : DescribeSkip

describe.skip(name, fn) #
Also under the alias: xdescribe(name, fn)

You can use describe.skip if you do not want to run a particular describe block:

describe('my beverage', () => {
  test('is delicious', () => {
    expect(myBeverage.delicious).toBeTruthy();
  });

  test('is not sour', () => {
    expect(myBeverage.sour).toBeFalsy();
  });
});

describe.skip('my other beverage', () => {
  // ... will be skipped
});

Using describe.skip is often just an easier alternative to temporarily commenting out a chunk of tests.

Add Jest : Expect : ToBeDefined

.toBeDefined() #
Use .toBeDefined to check that a variable is not undefined. For example, if you just want to check that a function fetchNewFlavorIdea() returns something, you can write:

test('there is a new flavor idea', () => {
  expect(fetchNewFlavorIdea()).toBeDefined();
});

You could write expect(fetchNewFlavorIdea()).not.toBe(undefined), but it's better practice to avoid referring to undefined directly in your code.

Add Jest : Expect : ToBeLessThanOrEqual

.toBeLessThanOrEqual(number) #
To compare floating point numbers, you can use toBeLessThanOrEqual. For example, if you want to test that ouncesPerCan() returns a value of at most 12 ounces, write:

test('ounces per can is at most 12', () => {
  expect(ouncesPerCan()).toBeLessThanOrEqual(12);
});

Add Jest : Expect : ToBeTruthy

.toBeTruthy() #
Use .toBeTruthy when you don't care what a value is, you just want to ensure a value is true in a boolean context. For example, let's say you have some application code that looks like:

drinkSomeLaCroix();
if (thirstInfo()) {
  drinkMoreLaCroix();
}

You may not care what thirstInfo returns, specifically - it might return true or a complex object, and your code would still work. So if you just want to test that thirstInfo will be truthy after drinking some La Croix, you could write:

test('drinking La Croix leads to having thirst info', () => {
  drinkSomeLaCroix();
  expect(thirstInfo()).toBeTruthy();
});

In JavaScript, there are six falsy values: false, 0, '', null, undefined, and NaN. Everything else is truthy.

Add Jest : Expect : ToBeGreaterThanOrEqual

.toBeGreaterThanOrEqual(number) #
To compare floating point numbers, you can use toBeGreaterThanOrEqual. For example, if you want to test that ouncesPerCan() returns a value of at least 12 ounces, write:

test('ounces per can is at least 12', () => {
  expect(ouncesPerCan()).toBeGreaterThanOrEqual(12);
});

Add Jest : Expect : ToBeCloseTo

.toBeCloseTo(number, numDigits) #
Using exact equality with floating point numbers is a bad idea. Rounding means that intuitive things fail. For example, this test fails:

test('adding works sanely with simple decimals', () => {
  expect(0.2 + 0.1).toBe(0.3); // Fails!
});

It fails because in JavaScript, 0.2 + 0.1 is actually 0.30000000000000004. Sorry.

Instead, use .toBeCloseTo. Use numDigits to control how many digits after the decimal point to check. For example, if you want to be sure that 0.2 + 0.1 is equal to 0.3 with a precision of 5 decimal digits, you can use this test:

test('adding works sanely with simple decimals', () => {
  expect(0.2 + 0.1).toBeCloseTo(0.3, 5);
});

The default for numDigits is 2, which has proved to be a good default in most cases.

Add Jest : Expect : ToBeLessThan

.toBeLessThan(number) #
To compare floating point numbers, you can use toBeLessThan. For example, if you want to test that ouncesPerCan() returns a value of less than 20 ounces, write:

test('ounces per can is less than 20', () => {
  expect(ouncesPerCan()).toBeLessThan(20);
});

Add Jest : Describe

describe(name, fn) #
describe(name, fn) creates a block that groups together several related tests in one "test suite". For example, if you have a myBeverage object that is supposed to be delicious but not sour, you could test it with:

const myBeverage = {
  delicious: true,
  sour: false,
};

describe('my beverage', () => {
  test('is delicious', () => {
    expect(myBeverage.delicious).toBeTruthy();
  });

  test('is not sour', () => {
    expect(myBeverage.sour).toBeFalsy();
  });
});

This isn't required - you can just write the test blocks directly at the top level. But this can be handy if you prefer your tests to be organized into groups.

You can also nest describe blocks if you have a hierarchy of tests:

const binaryStringToNumber = binString => {
  if (!/^[01]+$/.test(binString)) {
    throw new CustomError('Not a binary number.');
  }

  return parseInt(binString, 2);
};

describe('binaryStringToNumber', () => {
  describe('given an invalid binary string', () => {
    test('composed of non-numbers throws CustomError', () => {
      expect(() => binaryStringToNumber('abc')).toThrowError(CustomError);
    });

    test('with extra whitespace throws CustomError', () => {
      expect(() => binaryStringToNumber('  100')).toThrowError(CustomError);
    });
  });

  describe('given a valid binary string', () => {
    test('returns the correct number', () => {
      expect(binaryStringToNumber('100')).toBe(4);
    });
  });
});

Add Jest : Expect : ToMatch

.toMatch(regexpOrString) #
Use .toMatch to check that a string matches a regular expression.

For example, you might not know what exactly essayOnTheBestFlavor() returns, but you know it's a really long string, and the substring grapefruit should be in there somewhere. You can test this with:

describe('an essay on the best flavor', () => {
  test('mentions grapefruit', () => {
    expect(essayOnTheBestFlavor()).toMatch(/grapefruit/);
    expect(essayOnTheBestFlavor()).toMatch(new RegExp('grapefruit'));
  });
});

This matcher also accepts a string, which it will try to match:

describe('grapefruits are healthy', () => {
  test('grapefruits are a fruit', () => {
    expect('grapefruits').toMatch('fruit');
  });
});

Add Jest : BeforeEach

beforeEach(fn, timeout) #
Runs a function before each of the tests in this file runs. If the function returns a promise or is a generator, Jest waits for that promise to resolve before running the test.

Optionally, you can provide a timeout (in milliseconds) for specifying how long to wait before aborting. Note: The default timeout is 5 seconds.

This is often useful if you want to reset some global state that will be used by many tests.

For example:

const globalDatabase = makeGlobalDatabase();

beforeEach(() => {
  // Clears the database and adds some testing data.
  // Jest will wait for this promise to resolve before running tests.
  return globalDatabase.clear().then(() => {
    return globalDatabase.insert({testData: 'foo'});
  });
});

test('can find things', () => {
  return globalDatabase.find('thing', {}, results => {
    expect(results.length).toBeGreaterThan(0);
  });
});

test('can insert a thing', () => {
  return globalDatabase.insert('thing', makeThing(), response => {
    expect(response.success).toBeTruthy();
  });
});

Here the beforeEach ensures that the database is reset for each test.

If beforeEach is inside a describe block, it runs for each test in the describe block.

If you only need to run some setup code once, before any tests run, use beforeAll instead.

Add Jest : DescribeOnly

describe.only(name, fn) #
Also under the alias: fdescribe(name, fn)

You can use describe.only if you want to run only one describe block:

describe.only('my beverage', () => {
  test('is delicious', () => {
    expect(myBeverage.delicious).toBeTruthy();
  });

  test('is not sour', () => {
    expect(myBeverage.sour).toBeFalsy();
  });
});

describe('my other beverage', () => {
  // ... will be skipped
});

Add Jest : Expect : ToMatchSnapshot

.toMatchSnapshot(optionalString) #
This ensures that a value matches the most recent snapshot. Check out the Snapshot Testing guide for more information.

You can also specify an optional snapshot name. Otherwise, the name is inferred from the test.

Note: While snapshot testing is most commonly used with React components, any serializable value can be used as a snapshot.

Add Jest : Expect : ToBeGreatThan

.toBeGreaterThan(number) #
To compare floating point numbers, you can use toBeGreaterThan. For example, if you want to test that ouncesPerCan() returns a value of more than 10 ounces, write:

test('ounces per can is more than 10', () => {
  expect(ouncesPerCan()).toBeGreaterThan(10);
});

Add Jest : Expect : ToBe

toBe just checks that a value is what you expect. It uses Object.is to check exact equality.

For example, this code will validate some properties of the can object:

const can = {
  name: 'pamplemousse',
  ounces: 12,
};

describe('the can', () => {
  test('has 12 ounces', () => {
    expect(can.ounces).toBe(12);
  });

  test('has a sophisticated name', () => {
    expect(can.name).toBe('pamplemousse');
  });
});

Don't use toBe with floating-point numbers. For example, due to rounding, in JavaScript 0.2 + 0.1 is not strictly equal to 0.3. If you have floating point numbers, try .toBeCloseTo instead.

Add Jest : Expect : ToHaveLength

.toHaveLength(number) #
Use .toHaveLength to check that an object has a .length property and it is set to a certain numeric value.

This is especially useful for checking arrays or strings size.

expect([1, 2, 3]).toHaveLength(3);
expect('abc').toHaveLength(3);
expect('').not.toHaveLength(5);

Add Jest : Expect : ToEqual

.toEqual(value) #
Use .toEqual when you want to check that two objects have the same value. This matcher recursively checks the equality of all fields, rather than checking for object identity—this is also known as "deep equal". For example, toEqual and toBe behave differently in this test suite, so all the tests pass:

const can1 = {
  flavor: 'grapefruit',
  ounces: 12,
};
const can2 = {
  flavor: 'grapefruit',
  ounces: 12,
};

describe('the La Croix cans on my desk', () => {
  test('have all the same properties', () => {
    expect(can1).toEqual(can2);
  });
  test('are not the exact same can', () => {
    expect(can1).not.toBe(can2);
  });
});

Note: .toEqual won't perform a deep equality check for two errors. Only the message property of an Error is considered for equality. It is recommended to use the .toThrow matcher for testing against errors.

Add Jest : Expect : ToHaveBeenCalled

Also under the alias: .toBeCalled()

Use .toHaveBeenCalled to ensure that a mock function got called.

For example, let's say you have a drinkAll(drink, flavor) function that takes a drink function and applies it to all available beverages. You might want to check that drink gets called for 'lemon', but not for 'octopus', because 'octopus' flavor is really weird and why would anything be octopus-flavored? You can do that with this test suite:

describe('drinkAll', () => {
  test('drinks something lemon-flavored', () => {
    const drink = jest.fn();
    drinkAll(drink, 'lemon');
    expect(drink).toHaveBeenCalled();
  });

  test('does not drink something octopus-flavored', () => {
    const drink = jest.fn();
    drinkAll(drink, 'octopus');
    expect(drink).not.toHaveBeenCalled();
  });
});

express-controller: getbyid_middleware

  • modify function name;
  • format indent
  • format .exec()

exports.getProfessionById_middleWare = function (req, res, next, id) {
Profession.findById(id).exec((err, profession) => {
if (err) {
return next(err);
}
if (!profession) {
return next(new Error('Failed to get profession ' + id));
}
req.profession = profession;
next();
});
};

Add Jest : BeforeAll

beforeAll(fn, timeout) #
Runs a function before any of the tests in this file run. If the function returns a promise or is a generator, Jest waits for that promise to resolve before running tests.

Optionally, you can provide a timeout (in milliseconds) for specifying how long to wait before aborting. Note: The default timeout is 5 seconds.

This is often useful if you want to set up some global state that will be used by many tests.

For example:

const globalDatabase = makeGlobalDatabase();

beforeAll(() => {
  // Clears the database and adds some testing data.
  // Jest will wait for this promise to resolve before running tests.
  return globalDatabase.clear().then(() => {
    return globalDatabase.insert({testData: 'foo'});
  });
});

// Since we only set up the database once in this example, it's important
// that our tests don't modify it.
test('can find things', () => {
  return globalDatabase.find('thing', {}, results => {
    expect(results.length).toBeGreaterThan(0);
  });
});

Here the beforeAll ensures that the database is set up before tests run. If setup was synchronous, you could just do this without beforeAll. The key is that Jest will wait for a promise to resolve, so you can have asynchronous setup as well.

If beforeAll is inside a describe block, it runs at the beginning of the describe block.

If you want to run something before every test instead of before any test runs, use beforeEach instead.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.