Coder Social home page Coder Social logo

canechair.snippets's People

Contributors

lrse1 avatar simon8029 avatar

Stargazers

 avatar  avatar

Watchers

 avatar

canechair.snippets's Issues

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 : 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 : 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 : 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 : 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.

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 : 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 : 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 : 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 : 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 : 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 : 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 : 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 : 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 : 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 : 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 : 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 : 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 : 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 : 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();
  });
});

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},
    ]);
  });
});

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 : 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);
});

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 : 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 : 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 : 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 : 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();
});

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 : 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 : 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 : 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);
});

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.