From 23b93bc50b6e7a0b115184eef0790db26488398b Mon Sep 17 00:00:00 2001 From: Matt Phillips Date: Sat, 28 Apr 2018 19:23:25 +0100 Subject: [PATCH] Fix website docs (#5853) * Delete incorrect 22.4 docs * Add docs for 22.4.2 release * Add fix to changelog * Fix jest 22.4 docs for mockResolveValue * Lint --- CHANGELOG.md | 2 + .../versioned_docs/version-22.4/ExpectAPI.md | 1129 ----------------- .../version-22.4/JestCommunity.md | 32 - .../version-22.4/MockFunctionAPI.md | 324 ----- .../version-22.4/MockFunctions.md | 322 ----- .../version-22.4/MoreResources.md | 39 - .../versioned_docs/version-22.4/Puppeteer.md | 124 -- .../version-22.4/TestingFrameworks.md | 38 - .../version-22.4/TutorialReact.md | 3 +- .../version-22.4-sidebars.json | 39 - 10 files changed, 4 insertions(+), 2048 deletions(-) delete mode 100644 website/versioned_docs/version-22.4/ExpectAPI.md delete mode 100644 website/versioned_docs/version-22.4/JestCommunity.md delete mode 100644 website/versioned_docs/version-22.4/MockFunctionAPI.md delete mode 100644 website/versioned_docs/version-22.4/MockFunctions.md delete mode 100644 website/versioned_docs/version-22.4/MoreResources.md delete mode 100644 website/versioned_docs/version-22.4/Puppeteer.md delete mode 100644 website/versioned_docs/version-22.4/TestingFrameworks.md delete mode 100644 website/versioned_sidebars/version-22.4-sidebars.json diff --git a/CHANGELOG.md b/CHANGELOG.md index 66bce957b9ce..bffbade50bce 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -133,6 +133,8 @@ ([#5968](https://github.com/facebook/jest/pull/5968)) * `[jest-config]` Ensure that custom resolvers are used when resolving the configuration ([#5976](https://github.com/facebook/jest/pull/5976)) +* `[website]` Fix website docs + ([#5853](https://github.com/facebook/jest/pull/5853)) ### Chore & Maintenance diff --git a/website/versioned_docs/version-22.4/ExpectAPI.md b/website/versioned_docs/version-22.4/ExpectAPI.md deleted file mode 100644 index f9c8ef451826..000000000000 --- a/website/versioned_docs/version-22.4/ExpectAPI.md +++ /dev/null @@ -1,1129 +0,0 @@ ---- -id: version-22.4-expect -title: Expect -original_id: expect ---- - -When you're writing tests, you often need to check that values meet certain -conditions. `expect` gives you access to a number of "matchers" that let you -validate different things. - -## Methods - - - ---- - -## Reference - -### `expect(value)` - -The `expect` function is used every time you want to test a value. You will -rarely call `expect` by itself. Instead, you will use `expect` along with a -"matcher" function to assert something about a value. - -It's easier to understand this with an example. Let's say you have a method -`bestLaCroixFlavor()` which is supposed to return the string `'grapefruit'`. -Here's how you would test that: - -```js -test('the best flavor is grapefruit', () => { - expect(bestLaCroixFlavor()).toBe('grapefruit'); -}); -``` - -In this case, `toBe` is the matcher function. There are a lot of different -matcher functions, documented below, to help you test different things. - -The argument to `expect` should be the value that your code produces, and any -argument to the matcher should be the correct value. If you mix them up, your -tests will still work, but the error messages on failing tests will look -strange. - -### `expect.extend(matchers)` - -You can use `expect.extend` to add your own matchers to Jest. For example, let's -say that you're testing a number theory library and you're frequently asserting -that numbers are divisible by other numbers. You could abstract that into a -`toBeDivisibleBy` matcher: - -```js -expect.extend({ - toBeDivisibleBy(received, argument) { - const pass = received % argument == 0; - if (pass) { - return { - message: () => - `expected ${received} not to be divisible by ${argument}`, - pass: true, - }; - } else { - return { - message: () => `expected ${received} to be divisible by ${argument}`, - pass: false, - }; - } - }, -}); - -test('even and odd numbers', () => { - expect(100).toBeDivisibleBy(2); - expect(101).not.toBeDivisibleBy(2); -}); -``` - -Matchers should return an object with two keys. `pass` indicates whether there -was a match or not, and `message` provides a function with no arguments that -returns an error message in case of failure. Thus, when `pass` is false, -`message` should return the error message for when `expect(x).yourMatcher()` -fails. And when `pass` is true, `message` should return the error message for -when `expect(x).not.yourMatcher()` fails. - -These helper functions can be found on `this` inside a custom matcher: - -#### `this.isNot` - -A boolean to let you know this matcher was called with the negated `.not` -modifier allowing you to flip your assertion. - -#### `this.equals(a, b)` - -This is a deep-equality function that will return `true` if two objects have the -same values (recursively). - -#### `this.utils` - -There are a number of helpful tools exposed on `this.utils` primarily consisting -of the exports from -[`jest-matcher-utils`](https://github.com/facebook/jest/tree/master/packages/jest-matcher-utils). - -The most useful ones are `matcherHint`, `printExpected` and `printReceived` to -format the error messages nicely. For example, take a look at the implementation -for the `toBe` matcher: - -```js -const diff = require('jest-diff'); -expect.extend({ - toBe(received, expected) { - const pass = Object.is(received, expected); - - const message = pass - ? () => - this.utils.matcherHint('.not.toBe') + - '\n\n' + - `Expected value to not be (using Object.is):\n` + - ` ${this.utils.printExpected(expected)}\n` + - `Received:\n` + - ` ${this.utils.printReceived(received)}` - : () => { - const diffString = diff(expected, received, { - expand: this.expand, - }); - return ( - this.utils.matcherHint('.toBe') + - '\n\n' + - `Expected value to be (using Object.is):\n` + - ` ${this.utils.printExpected(expected)}\n` + - `Received:\n` + - ` ${this.utils.printReceived(received)}` + - (diffString ? `\n\nDifference:\n\n${diffString}` : '') - ); - }; - - return {actual: received, message, pass}; - }, -}); -``` - -This will print something like this: - -```bash - expect(received).toBe(expected) - - Expected value to be (using Object.is): - "banana" - Received: - "apple" -``` - -When an assertion fails, the error message should give as much signal as -necessary to the user so they can resolve their issue quickly. You should craft -a precise failure message to make sure users of your custom assertions have a -good developer experience. - -### `expect.anything()` - -`expect.anything()` matches anything but `null` or `undefined`. You can use it -inside `toEqual` or `toBeCalledWith` instead of a literal value. For example, if -you want to check that a mock function is called with a non-null argument: - -```js -test('map calls its argument with a non-null argument', () => { - const mock = jest.fn(); - [1].map(x => mock(x)); - expect(mock).toBeCalledWith(expect.anything()); -}); -``` - -### `expect.any(constructor)` - -`expect.any(constructor)` matches anything that was created with the given -constructor. You can use it inside `toEqual` or `toBeCalledWith` instead of a -literal value. For example, if you want to check that a mock function is called -with a number: - -```js -function randocall(fn) { - return fn(Math.floor(Math.random() * 6 + 1)); -} - -test('randocall calls its callback with a number', () => { - const mock = jest.fn(); - randocall(mock); - expect(mock).toBeCalledWith(expect.any(Number)); -}); -``` - -### `expect.arrayContaining(array)` - -`expect.arrayContaining(array)` matches a received array which contains all of -the elements in the expected array. That is, the expected array is a **subset** -of the received array. Therefore, it matches a received array which contains -elements that are **not** in the expected array. - -You can use it instead of a literal value: - -* in `toEqual` or `toBeCalledWith` -* to match a property in `objectContaining` or `toMatchObject` - -```js -describe('arrayContaining', () => { - const expected = ['Alice', 'Bob']; - it('matches even if received contains additional elements', () => { - expect(['Alice', 'Bob', 'Eve']).toEqual(expect.arrayContaining(expected)); - }); - it('does not match if received does not contain expected elements', () => { - expect(['Bob', 'Eve']).not.toEqual(expect.arrayContaining(expected)); - }); -}); -``` - -```js -describe('Beware of a misunderstanding! A sequence of dice rolls', () => { - const expected = [1, 2, 3, 4, 5, 6]; - it('matches even with an unexpected number 7', () => { - expect([4, 1, 6, 7, 3, 5, 2, 5, 4, 6]).toEqual( - expect.arrayContaining(expected), - ); - }); - it('does not match without an expected number 2', () => { - expect([4, 1, 6, 7, 3, 5, 7, 5, 4, 6]).not.toEqual( - expect.arrayContaining(expected), - ); - }); -}); -``` - -### `expect.assertions(number)` - -`expect.assertions(number)` verifies that a certain number of assertions are -called during a test. This is often useful when testing asynchronous code, in -order to make sure that assertions in a callback actually got called. - -For example, let's say that we have a function `doAsync` that receives two -callbacks `callback1` and `callback2`, it will asynchronously call both of them -in an unknown order. We can test this with: - -```js -test('doAsync calls both callbacks', () => { - expect.assertions(2); - function callback1(data) { - expect(data).toBeTruthy(); - } - function callback2(data) { - expect(data).toBeTruthy(); - } - - doAsync(callback1, callback2); -}); -``` - -The `expect.assertions(2)` call ensures that both callbacks actually get called. - -### `expect.hasAssertions()` - -`expect.hasAssertions()` verifies that at least one assertion is called during a -test. This is often useful when testing asynchronous code, in order to make sure -that assertions in a callback actually got called. - -For example, let's say that we have a few functions that all deal with state. -`prepareState` calls a callback with a state object, `validateState` runs on -that state object, and `waitOnState` returns a promise that waits until all -`prepareState` callbacks complete. We can test this with: - -```js -test('prepareState prepares a valid state', () => { - expect.hasAssertions(); - prepareState(state => { - expect(validateState(state)).toBeTruthy(); - }); - return waitOnState(); -}); -``` - -The `expect.hasAssertions()` call ensures that the `prepareState` callback -actually gets called. - -### `expect.not.arrayContaining(array)` - -`expect.not.arrayContaining(array)` matches a received array which contains none -of the elements in the expected array. That is, the expected array **is not a -subset** of the received array. - -It is the inverse of `expect.arrayContaining`. - -```js -describe('not.arrayContaining', () => { - const expected = ['Samantha']; - - it('matches if the actual array does not contain the expected elements', () => { - expect(['Alice', 'Bob', 'Eve']).toEqual( - expect.not.arrayContaining(expected), - ); - }); -}); -``` - -### `expect.not.objectContaining(object)` - -`expect.not.objectContaining(object)` matches any received object that does not -recursively match the expected properties. That is, the expected object **is not -a subset** of the received object. Therefore, it matches a received object which -contains properties that are **not** in the expected object. - -It is the inverse of `expect.objectContaining`. - -```js -describe('not.objectContaining', () => { - const expected = {foo: 'bar'}; - - it('matches if the actual object does not contain expected key: value pairs', () => { - expect({bar: 'baz'}).toEqual(expect.not.objectContaining(expected)); - }); -}); -``` - -### `expect.not.stringContaining(string)` - -`expect.not.stringContaining(string)` matches any received string that does not -contain the exact expected string. - -It is the inverse of `expect.stringContaining`. - -```js -describe('not.stringContaining', () => { - const expected = 'Hello world!'; - - it('matches if the actual string does not contain the expected substring', () => { - expect('How are you?').toEqual(expect.not.stringContaining(expected)); - }); -}); -``` - -### `expect.not.stringMatching(regexp)` - -`expect.not.stringMatching(regexp)` matches any received string that does not -match the expected regexp. - -It is the inverse of `expect.stringMatching`. - -```js -describe('not.stringMatching', () => { - const expected = /Hello world!/; - - it('matches if the actual string does not match the expected regex', () => { - expect('How are you?').toEqual(expect.not.stringMatching(expected)); - }); -}); -``` - -### `expect.objectContaining(object)` - -`expect.objectContaining(object)` matches any received object that recursively -matches the expected properties. That is, the expected object is a **subset** of -the received object. Therefore, it matches a received object which contains -properties that are **not** in the expected object. - -Instead of literal property values in the expected object, you can use matchers, -`expect.anything()`, and so on. - -For example, let's say that we expect an `onPress` function to be called with an -`Event` object, and all we need to verify is that the event has `event.x` and -`event.y` properties. We can do that with: - -```js -test('onPress gets called with the right thing', () => { - const onPress = jest.fn(); - simulatePresses(onPress); - expect(onPress).toBeCalledWith( - expect.objectContaining({ - x: expect.any(Number), - y: expect.any(Number), - }), - ); -}); -``` - -### `expect.stringContaining(string)` - -`expect.stringContaining(string)` matches any received string that contains the -exact expected string. - -### `expect.stringMatching(regexp)` - -`expect.stringMatching(regexp)` matches any received string that matches the -expected regexp. - -You can use it instead of a literal value: - -* in `toEqual` or `toBeCalledWith` -* to match an element in `arrayContaining` -* to match a property in `objectContaining` or `toMatchObject` - -This example also shows how you can nest multiple asymmetric matchers, with -`expect.stringMatching` inside the `expect.arrayContaining`. - -```js -describe('stringMatching in arrayContaining', () => { - const expected = [ - expect.stringMatching(/^Alic/), - expect.stringMatching(/^[BR]ob/), - ]; - it('matches even if received contains additional elements', () => { - expect(['Alicia', 'Roberto', 'Evelina']).toEqual( - expect.arrayContaining(expected), - ); - }); - it('does not match if received does not contain expected elements', () => { - expect(['Roberto', 'Evelina']).not.toEqual( - expect.arrayContaining(expected), - ); - }); -}); -``` - -### `expect.addSnapshotSerializer(serializer)` - -You can call `expect.addSnapshotSerializer` to add a module that formats -application-specific data structures. - -For an individual test file, an added module precedes any modules from -`snapshotSerializers` configuration, which precede the default snapshot -serializers for built-in JavaScript types and for React elements. The last -module added is the first module tested. - -```js -import serializer from 'my-serializer-module'; -expect.addSnapshotSerializer(serializer); - -// affects expect(value).toMatchSnapshot() assertions in the test file -``` - -If you add a snapshot serializer in individual test files instead of to adding -it to `snapshotSerializers` configuration: - -* You make the dependency explicit instead of implicit. -* You avoid limits to configuration that might cause you to eject from - [create-react-app](https://github.com/facebookincubator/create-react-app). - -See [configuring Jest](Configuration.md#snapshotserializers-array-string) for -more information. - -### `.not` - -If you know how to test something, `.not` lets you test its opposite. For -example, this code tests that the best La Croix flavor is not coconut: - -```js -test('the best flavor is not coconut', () => { - expect(bestLaCroixFlavor()).not.toBe('coconut'); -}); -``` - -### `.resolves` - -Use `resolves` to unwrap the value of a fulfilled promise so any other matcher -can be chained. If the promise is rejected the assertion fails. - -For example, this code tests that the promise resolves and that the resulting -value is `'lemon'`: - -```js -test('resolves to lemon', () => { - // make sure to add a return statement - return expect(Promise.resolve('lemon')).resolves.toBe('lemon'); -}); -``` - -Note that, since you are still testing promises, the test is still asynchronous. -Hence, you will need to [tell Jest to wait](TestingAsyncCode.md#promises) by -returning the unwrapped assertion. - -Alternatively, you can use `async/await` in combination with `.resolves`: - -```js -test('resolves to lemon', async () => { - await expect(Promise.resolve('lemon')).resolves.toBe('lemon'); - await expect(Promise.resolve('lemon')).resolves.not.toBe('octopus'); -}); -``` - -### `.rejects` - -Use `.rejects` to unwrap the reason of a rejected promise so any other matcher -can be chained. If the promise is fulfilled the assertion fails. - -For example, this code tests that the promise rejects with reason `'octopus'`: - -```js -test('rejects to octopus', () => { - // make sure to add a return statement - return expect(Promise.reject(new Error('octopus'))).rejects.toThrow( - 'octopus', - ); -}); -``` - -Note that, since you are still testing promises, the test is still asynchronous. -Hence, you will need to [tell Jest to wait](TestingAsyncCode.md#promises) by -returning the unwrapped assertion. - -Alternatively, you can use `async/await` in combination with `.rejects`. - -```js -test('rejects to octopus', async () => { - await expect(Promise.reject(new Error('octopus'))).rejects.toThrow('octopus'); -}); -``` - -### `.toBe(value)` - -`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: - -```js -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. - -### `.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: - -```js -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(); - }); -}); -``` - -### `.toHaveBeenCalledTimes(number)` - -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: - -```js -test('drinkEach drinks each drink', () => { - const drink = jest.fn(); - drinkEach(drink, ['lemon', 'octopus']); - expect(drink).toHaveBeenCalledTimes(2); -}); -``` - -### `.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: - -```js -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); -}); -``` - -### `.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: - -```js -test('applying to all flavors does mango last', () => { - const drink = jest.fn(); - applyToAllFlavors(drink); - expect(drink).toHaveBeenLastCalledWith('mango'); -}); -``` - -### `.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: - -```js -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: - -```js -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. - -### `.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: - -```js -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. - -### `.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: - -```js -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: - -```js -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. - -### `.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: - -```js -test('ounces per can is more than 10', () => { - expect(ouncesPerCan()).toBeGreaterThan(10); -}); -``` - -### `.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: - -```js -test('ounces per can is at least 12', () => { - expect(ouncesPerCan()).toBeGreaterThanOrEqual(12); -}); -``` - -### `.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: - -```js -test('ounces per can is less than 20', () => { - expect(ouncesPerCan()).toBeLessThan(20); -}); -``` - -### `.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: - -```js -test('ounces per can is at most 12', () => { - expect(ouncesPerCan()).toBeLessThanOrEqual(12); -}); -``` - -### `.toBeInstanceOf(Class)` - -Use `.toBeInstanceOf(Class)` to check that an object is an instance of a class. -This matcher uses `instanceof` underneath. - -```js -class A {} - -expect(new A()).toBeInstanceOf(A); -expect(() => {}).toBeInstanceOf(Function); -expect(new A()).toBeInstanceOf(Function); // throws -``` - -### `.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. - -```js -function bloop() { - return null; -} - -test('bloop returns null', () => { - expect(bloop()).toBeNull(); -}); -``` - -### `.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: - -```js -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: - -```js -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. - -### `.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: - -```js -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. - -### `.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: - -```js -test('the flavor list contains lime', () => { - expect(getAllFlavors()).toContain('lime'); -}); -``` - -### `.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. - -```js -describe('my beverage', () => { - test('is delicious and not sour', () => { - const myBeverage = {delicious: true, sour: false}; - expect(myBeverages()).toContainEqual(myBeverage); - }); -}); -``` - -### `.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: - -```js -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. - -### `.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. - -```js -expect([1, 2, 3]).toHaveLength(3); -expect('abc').toHaveLength(3); -expect('').not.toHaveLength(5); -``` - -### `.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: - -```js -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: - -```js -describe('grapefruits are healthy', () => { - test('grapefruits are a fruit', () => { - expect('grapefruits').toMatch('fruit'); - }); -}); -``` - -### `.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. - -```js -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); -}); -``` - -```js -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}, - ]); - }); -}); -``` - -### `.toHaveProperty(keyPath, value)` - -Use `.toHaveProperty` to check if property at provided reference `keyPath` -exists for an object. For checking deeply nested properties in an object you may -use -[dot notation](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors) -or an array containing the keyPath for deep references. - -Optionally, you can provide a `value` to check if it's equal to the value -present at `keyPath` on the target object. This matcher uses 'deep equality' -(like `toEqual()`) and recursively checks the equality of all fields. - -The following example contains a `houseForSale` object with nested properties. -We are using `toHaveProperty` to check for the existence and values of various -properties in the object. - -```js -// Object containing house features to be tested -const houseForSale = { - bath: true, - bedrooms: 4, - kitchen: { - amenities: ['oven', 'stove', 'washer'], - area: 20, - wallColor: 'white', - 'nice.oven': true, - }, -}; - -test('this house has my desired features', () => { - // Simple Referencing - expect(houseForSale).toHaveProperty('bath'); - expect(houseForSale).toHaveProperty('bedrooms', 4); - - expect(houseForSale).not.toHaveProperty('pool'); - - // Deep referencing using dot notation - expect(houseForSale).toHaveProperty('kitchen.area', 20); - expect(houseForSale).toHaveProperty('kitchen.amenities', [ - 'oven', - 'stove', - 'washer', - ]); - - expect(houseForSale).not.toHaveProperty('kitchen.open'); - - // Deep referencing using an array containing the keyPath - expect(houseForSale).toHaveProperty(['kitchen', 'area'], 20); - expect(houseForSale).toHaveProperty( - ['kitchen', 'amenities'], - ['oven', 'stove', 'washer'], - ); - expect(houseForSale).toHaveProperty(['kitchen', 'amenities', 0], 'oven'); - expect(houseForSale).toHaveProperty(['kitchen', 'nice.oven']); - expect(houseForSale).not.toHaveProperty(['kitchen', 'open']); -}); -``` - -### `.toMatchSnapshot(optionalString)` - -This ensures that a value matches the most recent snapshot. Check out -[the Snapshot Testing guide](SnapshotTesting.md) 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._ - -### `.toThrow(error)` - -Also under the alias: `.toThrowError(error)` - -Use `.toThrow` to test that a function throws when it is called. For example, if -we want to test that `drinkFlavor('octopus')` throws, because octopus flavor is -too disgusting to drink, we could write: - -```js -test('throws on octopus', () => { - expect(() => { - drinkFlavor('octopus'); - }).toThrow(); -}); -``` - -If you want to test that a specific error gets thrown, you can provide an -argument to `toThrow`. The argument can be a string that should be contained in -the error message, a class for the error, or a regex that should match the error -message. For example, let's say that `drinkFlavor` is coded like this: - -```js -function drinkFlavor(flavor) { - if (flavor == 'octopus') { - throw new DisgustingFlavorError('yuck, octopus flavor'); - } - // Do some other stuff -} -``` - -We could test this error gets thrown in several ways: - -```js -test('throws on octopus', () => { - function drinkOctopus() { - drinkFlavor('octopus'); - } - - // Test that the error message says "yuck" somewhere: these are equivalent - expect(drinkOctopus).toThrowError(/yuck/); - expect(drinkOctopus).toThrowError('yuck'); - - // Test the exact error message - expect(drinkOctopus).toThrowError(/^yuck, octopus flavor$/); - - // Test that we get a DisgustingFlavorError - expect(drinkOctopus).toThrowError(DisgustingFlavorError); -}); -``` - -> Note: You must wrap the code in a function, otherwise the error will not be -> caught and the assertion will fail. - -### `.toThrowErrorMatchingSnapshot()` - -Use `.toThrowErrorMatchingSnapshot` to test that a function throws an error -matching the most recent snapshot when it is called. For example, let's say you -have a `drinkFlavor` function that throws whenever the flavor is `'octopus'`, -and is coded like this: - -```js -function drinkFlavor(flavor) { - if (flavor == 'octopus') { - throw new DisgustingFlavorError('yuck, octopus flavor'); - } - // Do some other stuff -} -``` - -The test for this function will look this way: - -```js -test('throws on octopus', () => { - function drinkOctopus() { - drinkFlavor('octopus'); - } - - expect(drinkOctopus).toThrowErrorMatchingSnapshot(); -}); -``` - -And it will generate the following snapshot: - -```js -exports[`drinking flavors throws on octopus 1`] = `"yuck, octopus flavor"`; -``` - -Check out -[React Tree Snapshot Testing](http://facebook.github.io/jest/blog/2016/07/27/jest-14.html) -for more information on snapshot testing. diff --git a/website/versioned_docs/version-22.4/JestCommunity.md b/website/versioned_docs/version-22.4/JestCommunity.md deleted file mode 100644 index afbe88026529..000000000000 --- a/website/versioned_docs/version-22.4/JestCommunity.md +++ /dev/null @@ -1,32 +0,0 @@ ---- -title: Jest Community -id: version-22.4-jest-community -original_id: jest-community ---- - -The community around Jest is working hard to make the testing experience even -greater. - -[jest-community](https://github.com/jest-community) is a new GitHub organization -for high quality Jest additions curated by Jest maintainers and collaborators. -It already features some of our favorite projects, to name a few: - -* [vscode-jest](https://github.com/jest-community/vscode-jest) -* [jest-extended](https://github.com/jest-community/jest-extended) -* [eslint-plugin-jest](https://github.com/jest-community/eslint-plugin-jest) -* [awesome-jest](https://github.com/jest-community/awesome-jest) - -Community projects under one organisation are a great way for Jest to experiment -with new ideas/techniques and approaches. Encourage contributions from the -community and publish contributions independently at a faster pace. - -The jest-community org maintains an -[awesome-jest](https://github.com/jest-community/awesome-jest) list of great -projects and resources related to Jest, this includes all projects not just the -ones in the jest-community org. - -If you have something awesome to share, feel free to reach out to us! We'd love -to share your project on the awesome-jest list -([send a PR here](https://github.com/jest-community/awesome-jest/pulls)) or if -you would like to transfer your project to the jest-community org reachout to -one of the owners of the org. diff --git a/website/versioned_docs/version-22.4/MockFunctionAPI.md b/website/versioned_docs/version-22.4/MockFunctionAPI.md deleted file mode 100644 index 1985200ce568..000000000000 --- a/website/versioned_docs/version-22.4/MockFunctionAPI.md +++ /dev/null @@ -1,324 +0,0 @@ ---- -id: version-22.4-mock-function-api -title: Mock Functions -original_id: mock-function-api ---- - -Mock functions are also known as "spies", because they let you spy on the -behavior of a function that is called indirectly by some other code, rather than -just testing the output. You can create a mock function with `jest.fn()`. If no -implementation is given, the mock function will return `undefined` when invoked. - -## Methods - - - ---- - -## Reference - -### `mockFn.getMockName()` - -Returns the mock name string set by calling `mockFn.mockName(value)`. - -### `mockFn.mock.calls` - -An array that represents all calls that have been made into this mock function. -Each call is represented by an array of arguments that were passed during the -call. - -For example: A mock function `f` that has been called twice, with the arguments -`f('arg1', 'arg2')`, and then with the arguments `f('arg3', 'arg4')` would have -a `mock.calls` array that looks like this: - -```js -[['arg1', 'arg2'], ['arg3', 'arg4']]; -``` - -### `mockFn.mock.instances` - -An array that contains all the object instances that have been instantiated from -this mock function using `new`. - -For example: A mock function that has been instantiated twice would have the -following `mock.instances` array: - -```js -const mockFn = jest.fn(); - -const a = new mockFn(); -const b = new mockFn(); - -mockFn.mock.instances[0] === a; // true -mockFn.mock.instances[1] === b; // true -``` - -### `mockFn.mockClear()` - -Resets all information stored in the [`mockFn.mock.calls`](#mockfn-mock-calls) -and [`mockFn.mock.instances`](#mockfn-mock-instances) arrays. - -Often this is useful when you want to clean up a mock's usage data between two -assertions. - -Beware that `mockClear` will replace `mockFn.mock`, not just -[`mockFn.mock.calls`](#mockfn-mock-calls) and -[`mockFn.mock.instances`](#mockfn-mock-instances). You should therefore avoid -assigning `mockFn.mock` to other variables, temporary or not, to make sure you -don't access stale data. - -The [`clearMocks`](configuration.html#clearmocks-boolean) configuration option -is available to clear mocks automatically between tests. - -### `mockFn.mockReset()` - -Resets all information stored in the mock, including any initial implementation -and mock name given. - -This is useful when you want to completely restore a mock back to its initial -state. - -Beware that `mockReset` will replace `mockFn.mock`, not just -[`mockFn.mock.calls`](#mockfn-mock-calls) and -[`mockFn.mock.instances`](#mockfn-mock-instances). You should therefore avoid -assigning `mockFn.mock` to other variables, temporary or not, to make sure you -don't access stale data. - -### `mockFn.mockRestore()` - -Removes the mock and restores the initial implementation. - -This is useful when you want to mock functions in certain test cases and restore -the original implementation in others. - -Beware that `mockFn.mockRestore` only works when mock was created with -`jest.spyOn`. Thus you have to take care of restoration yourself when manually -assigning `jest.fn()`. - -The [`restoreMocks`](configuration.html#restoremocks-boolean) configuration -option is available to restore mocks automatically between tests. - -### `mockFn.mockImplementation(fn)` - -Accepts a function that should be used as the implementation of the mock. The -mock itself will still record all calls that go into and instances that come -from itself – the only difference is that the implementation will also be -executed when the mock is called. - -_Note: `jest.fn(implementation)` is a shorthand for -`jest.fn().mockImplementation(implementation)`._ - -For example: - -```js -const mockFn = jest.fn().mockImplementation(scalar => 42 + scalar); -// or: jest.fn(scalar => 42 + scalar); - -const a = mockFn(0); -const b = mockFn(1); - -a === 42; // true -b === 43; // true - -mockFn.mock.calls[0][0] === 0; // true -mockFn.mock.calls[1][0] === 1; // true -``` - -`mockImplementation` can also be used to mock class constructors: - -```js -// SomeClass.js -module.exports = class SomeClass { - m(a, b) {} -}; - -// OtherModule.test.js -jest.mock('./SomeClass'); // this happens automatically with automocking -const SomeClass = require('./SomeClass'); -const mMock = jest.fn(); -SomeClass.mockImplementation(() => { - return { - m: mMock, - }; -}); - -const some = new SomeClass(); -some.m('a', 'b'); -console.log('Calls to m: ', mMock.mock.calls); -``` - -### `mockFn.mockImplementationOnce(fn)` - -Accepts a function that will be used as an implementation of the mock for one -call to the mocked function. Can be chained so that multiple function calls -produce different results. - -```js -const myMockFn = jest - .fn() - .mockImplementationOnce(cb => cb(null, true)) - .mockImplementationOnce(cb => cb(null, false)); - -myMockFn((err, val) => console.log(val)); // true - -myMockFn((err, val) => console.log(val)); // false -``` - -When the mocked function runs out of implementations defined with -mockImplementationOnce, it will execute the default implementation set with -`jest.fn(() => defaultValue)` or `.mockImplementation(() => defaultValue)` if -they were called: - -```js -const myMockFn = jest - .fn(() => 'default') - .mockImplementationOnce(() => 'first call') - .mockImplementationOnce(() => 'second call'); - -// 'first call', 'second call', 'default', 'default' -console.log(myMockFn(), myMockFn(), myMockFn(), myMockFn()); -``` - -### `mockFn.mockName(value)` - -Accepts a string to use in test result output in place of "jest.fn()" to -indicate which mock function is being referenced. - -For example: - -```js -const mockFn = jest.fn().mockName('mockedFunction'); -// mockFn(); -expect(mockFn).toHaveBeenCalled(); -``` - -Will result in this error: - -```bash - expect(mockedFunction).toHaveBeenCalled() - - Expected mock function to have been called. -``` - -### `mockFn.mockReturnThis()` - -Just a simple sugar function for: - -```js -jest.fn(function() { - return this; -}); -``` - -### `mockFn.mockReturnValue(value)` - -Accepts a value that will be returned whenever the mock function is called. - -```js -const mock = jest.fn(); -mock.mockReturnValue(42); -mock(); // 42 -mock.mockReturnValue(43); -mock(); // 43 -``` - -### `mockFn.mockReturnValueOnce(value)` - -Accepts a value that will be returned for one call to the mock function. Can be -chained so that successive calls to the mock function return different values. -When there are no more `mockReturnValueOnce` values to use, calls will return a -value specified by `mockReturnValue`. - -```js -const myMockFn = jest - .fn() - .mockReturnValue('default') - .mockReturnValueOnce('first call') - .mockReturnValueOnce('second call'); - -// 'first call', 'second call', 'default', 'default' -console.log(myMockFn(), myMockFn(), myMockFn(), myMockFn()); -``` - -### `mockFn.mockResolvedValue(value)` - -Simple sugar function for: - -```js -jest.fn().mockReturnValue(Promise.resolve(value)); -``` - -Useful to mock async functions in async tests: - -```js -test('async test', async () => { - const asyncMock = jest.fn().mockResolvedValue(43); - - await asyncMock(); // 43 -}); -``` - -### `mockFn.mockResolvedValueOnce(value)` - -Simple sugar function for: - -```js -jest.fn().mockReturnValueOnce(Promise.resolve(value)); -``` - -Useful to resolve different values over multiple async calls: - -```js -test('async test', async () => { - const asyncMock = jest - .fn() - .mockResolvedValue('default') - .mockResolvedValueOnce('first call') - .mockResolvedValueOnce('second call'); - - await asyncMock(); // first call - await asyncMock(); // second call - await asyncMock(); // default - await asyncMock(); // default -}); -``` - -### `mockFn.mockRejectedValue(value)` - -Simple sugar function for: - -```js -jest.fn().mockReturnValue(Promise.reject(value)); -``` - -Useful to create async mock functions that will always reject: - -```js -test('async test', async () => { - const asyncMock = jest.fn().mockRejectedValue(new Error('Async error')); - - await asyncMock(); // throws "Async error" -}); -``` - -### `mockFn.mockRejectedValueOnce(value)` - -Simple sugar function for: - -```js -jest.fn().mockReturnValueOnce(Promise.reject(value)); -``` - -Example usage: - -```js -test('async test', async () => { - const asyncMock = jest - .fn() - .mockResolvedValueOnce('first call') - .mockRejectedValueOnce(new Error('Async error')); - - await asyncMock(); // first call - await asyncMock(); // throws "Async error" -}); -``` diff --git a/website/versioned_docs/version-22.4/MockFunctions.md b/website/versioned_docs/version-22.4/MockFunctions.md deleted file mode 100644 index cc0ae2874eae..000000000000 --- a/website/versioned_docs/version-22.4/MockFunctions.md +++ /dev/null @@ -1,322 +0,0 @@ ---- -id: version-22.4-mock-functions -title: Mock Functions -original_id: mock-functions ---- - -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. - -There are two ways to mock functions: Either by creating a mock function to use -in test code, or writing a [`manual mock`](ManualMocks.md) to override a module -dependency. - -## Using a mock function - -Let's imagine we're testing an implementation of a function `forEach`, which -invokes a callback for each item in a supplied array. - -```javascript -function forEach(items, callback) { - for (let index = 0; index < items.length; index++) { - callback(items[index]); - } -} -``` - -To test this function, we can use a mock function, and inspect the mock's state -to ensure the callback is invoked as expected. - -```javascript -const mockCallback = jest.fn(); -forEach([0, 1], mockCallback); - -// The mock function is called twice -expect(mockCallback.mock.calls.length).toBe(2); - -// The first argument of the first call to the function was 0 -expect(mockCallback.mock.calls[0][0]).toBe(0); - -// The first argument of the second call to the function was 1 -expect(mockCallback.mock.calls[1][0]).toBe(1); -``` - -## `.mock` property - -All mock functions have this special `.mock` property, which is where data about -how the function has been called is kept. The `.mock` property also tracks the -value of `this` for each call, so it is possible to inspect this as well: - -```javascript -const myMock = jest.fn(); - -const a = new myMock(); -const b = {}; -const bound = myMock.bind(b); -bound(); - -console.log(myMock.mock.instances); -// > [ , ] -``` - -These mock members are very useful in tests to assert how these functions get -called, or instantiated: - -```javascript -// The function was called exactly once -expect(someMockFunction.mock.calls.length).toBe(1); - -// The first arg of the first call to the function was 'first arg' -expect(someMockFunction.mock.calls[0][0]).toBe('first arg'); - -// The second arg of the first call to the function was 'second arg' -expect(someMockFunction.mock.calls[0][1]).toBe('second arg'); - -// This function was instantiated exactly twice -expect(someMockFunction.mock.instances.length).toBe(2); - -// The object returned by the first instantiation of this function -// had a `name` property whose value was set to 'test' -expect(someMockFunction.mock.instances[0].name).toEqual('test'); -``` - -## Mock Return Values - -Mock functions can also be used to inject test values into your code during a -test: - -```javascript -const myMock = jest.fn(); -console.log(myMock()); -// > undefined - -myMock - .mockReturnValueOnce(10) - .mockReturnValueOnce('x') - .mockReturnValue(true); - -console.log(myMock(), myMock(), myMock(), myMock()); -// > 10, 'x', true, true -``` - -Mock functions are also very effective in code that uses a functional -continuation-passing style. Code written in this style helps avoid the need for -complicated stubs that recreate behavior of the real component they're standing -in for, in favor of injecting values directly into the test right before they're -used. - -```javascript -const filterTestFn = jest.fn(); - -// Make the mock return `true` for the first call, -// and `false` for the second call -filterTestFn.mockReturnValueOnce(true).mockReturnValueOnce(false); - -const result = [11, 12].filter(filterTestFn); - -console.log(result); -// > [11] -console.log(filterTestFn.mock.calls); -// > [ [11], [12] ] -``` - -Most real-world examples actually involve getting ahold of a mock function on a -dependent component and configuring that, but the technique is the same. In -these cases, try to avoid the temptation to implement logic inside of any -function that's not directly being tested. - -## Mocking Modules - -Suppose we have a class that fetches users from our API. The class uses -[axios](https://github.com/axios/axios) to call the API then returns the `data` -attribute which contains all the users: - -```js -// users.js -import axios from 'axios'; - -class Users { - static all() { - return axios.get('/users.json').then(resp => resp.data); - } -} - -export default Users; -``` - -Now, in order to test this method without actually hitting the API (and thus -creating slow and fragile tests), we can use the `jest.mock(...)` function to -automatically mock the axios module. - -Once we mock the module we can provide a `mockReturnValue` for `.get` that -returns the data we want our test to assert against. In effect, we are saying -that we want axios.get('/users.json') to return a fake response. - -```js -// users.test.js -import axios from 'axios'; -import Users from './users'; - -jest.mock('axios'); - -test('should fetch users', () => { - const resp = {data: [{name: 'Bob'}]}; - axios.get.mockResolvedValue(resp); - - // or you could use the follwing depending on your use case: - // axios.get.mockImplementation(() => Promise.resolve(resp)) - - return Users.all().then(users => expect(users).toEqual(resp.data)); -}); -``` - -## Mock Implementations - -Still, there are cases where it's useful to go beyond the ability to specify -return values and full-on replace the implementation of a mock function. This -can be done with `jest.fn` or the `mockImplementationOnce` method on mock -functions. - -```javascript -const myMockFn = jest.fn(cb => cb(null, true)); - -myMockFn((err, val) => console.log(val)); -// > true - -myMockFn((err, val) => console.log(val)); -// > true -``` - -The `mockImplementation` method is useful when you need to define the default -implementation of a mock function that is created from another module: - -```js -// foo.js -module.exports = function() { - // some implementation; -}; - -// test.js -jest.mock('../foo'); // this happens automatically with automocking -const foo = require('../foo'); - -// foo is a mock function -foo.mockImplementation(() => 42); -foo(); -// > 42 -``` - -When you need to recreate a complex behavior of a mock function such that -multiple function calls produce different results, use the -`mockImplementationOnce` method: - -```javascript -const myMockFn = jest - .fn() - .mockImplementationOnce(cb => cb(null, true)) - .mockImplementationOnce(cb => cb(null, false)); - -myMockFn((err, val) => console.log(val)); -// > true - -myMockFn((err, val) => console.log(val)); -// > false -``` - -When the mocked function runs out of implementations defined with -`mockImplementationOnce`, it will execute the default implementation set with -`jest.fn` (if it is defined): - -```javascript -const myMockFn = jest - .fn(() => 'default') - .mockImplementationOnce(() => 'first call') - .mockImplementationOnce(() => 'second call'); - -console.log(myMockFn(), myMockFn(), myMockFn(), myMockFn()); -// > 'first call', 'second call', 'default', 'default' -``` - -For cases where we have methods that are typically chained (and thus always need -to return `this`), we have a sugary API to simplify this in the form of a -`.mockReturnThis()` function that also sits on all mocks: - -```javascript -const myObj = { - myMethod: jest.fn().mockReturnThis(), -}; - -// is the same as - -const otherObj = { - myMethod: jest.fn(function() { - return this; - }), -}; -``` - -## Mock Names - -You can optionally provide a name for your mock functions, which will be -displayed instead of "jest.fn()" in test error output. Use this if you want to -be able to quickly identify the mock function reporting an error in your test -output. - -```javascript -const myMockFn = jest - .fn() - .mockReturnValue('default') - .mockImplementation(scalar => 42 + scalar) - .mockName('add42'); -``` - -## Custom Matchers - -Finally, in order to make it simpler to assert how mock functions have been -called, we've added some custom matcher functions for you: - -```javascript -// The mock function was called at least once -expect(mockFunc).toBeCalled(); - -// The mock function was called at least once with the specified args -expect(mockFunc).toBeCalledWith(arg1, arg2); - -// The last call to the mock function was called with the specified args -expect(mockFunc).lastCalledWith(arg1, arg2); - -// All calls and the name of the mock is written as a snapshot -expect(mockFunc).toMatchSnapshot(); -``` - -These matchers are really just sugar for common forms of inspecting the `.mock` -property. You can always do this manually yourself if that's more to your taste -or if you need to do something more specific: - -```javascript -// The mock function was called at least once -expect(mockFunc.mock.calls.length).toBeGreaterThan(0); - -// The mock function was called at least once with the specified args -expect(mockFunc.mock.calls).toContain([arg1, arg2]); - -// The last call to the mock function was called with the specified args -expect(mockFunc.mock.calls[mockFunc.mock.calls.length - 1]).toEqual([ - arg1, - arg2, -]); - -// The first arg of the last call to the mock function was `42` -// (note that there is no sugar helper for this specific of an assertion) -expect(mockFunc.mock.calls[mockFunc.mock.calls.length - 1][0]).toBe(42); - -// A snapshot will check that a mock was invoked the same number of times, -// in the same order, with the same arguments. It will also assert on the name. -expect(mockFunc.mock.calls).toEqual([[arg1, arg2]]); -expect(mockFunc.mock.getMockName()).toBe('a mock name'); -``` - -For a complete list of matchers, check out the [reference docs](ExpectAPI.md). diff --git a/website/versioned_docs/version-22.4/MoreResources.md b/website/versioned_docs/version-22.4/MoreResources.md deleted file mode 100644 index 860f3ba64458..000000000000 --- a/website/versioned_docs/version-22.4/MoreResources.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -id: version-22.4-more-resources -title: More Resources -original_id: more-resources ---- - -By now you should have a good idea of how Jest can make it easy to test your -applications. If you're interested in learning more, here's some related stuff -you might want to check out. - -### Browse the docs - -* Learn about [Snapshot Testing](SnapshotTesting.md), - [Mock Functions](MockFunctions.md), and more in our in-depth guides. -* Migrate your existing tests to Jest by following our - [migration guide](MigrationGuide.md). -* Learn how to [configure Jest](Configuration.md). -* Look at the full [API Reference](GlobalAPI.md). -* [Troubleshoot](Troubleshooting.md) problems with Jest. - -### Learn by example - -You will find a number of example test cases in the -[`examples`](https://github.com/facebook/jest/tree/master/examples) folder on -GitHub. You can also learn from the excellent tests used by the -[React](https://github.com/facebook/react/tree/master/packages/react/src/__tests__), -[Relay](https://github.com/facebook/relay/tree/master/packages/react-relay/modern/__tests__), -and -[React Native](https://github.com/facebook/react-native/tree/master/Libraries/Animated/src/__tests__) -projects. - -### Join the community - -Ask questions and find answers from other Jest users like you. -[Reactiflux](http://www.reactiflux.com/) is a Discord chat where a lot of Jest -discussion happens. Check out the [#jest](https://discord.gg/MWRhKCj) channel. - -Follow the [Jest Twitter account](https://twitter.com/fbjest) and -[blog](/jest/blog/) to find out what's happening in the world of Jest. diff --git a/website/versioned_docs/version-22.4/Puppeteer.md b/website/versioned_docs/version-22.4/Puppeteer.md deleted file mode 100644 index 75ec05934efe..000000000000 --- a/website/versioned_docs/version-22.4/Puppeteer.md +++ /dev/null @@ -1,124 +0,0 @@ ---- -id: version-22.4-puppeteer -title: Using with puppeteer -original_id: puppeteer ---- - -With the [Global Setup/Teardown](Configuration.md#globalsetup-string) and -[Async Test Environment](Configuration.md#testenvironment-string) APIs, Jest can -work smoothly with [puppeteer](https://github.com/GoogleChrome/puppeteer). - -## Use Puppeteer Preset - -[Jest Puppeteer Preset](https://github.com/smooth-code/jest-puppeteer) provides -all required configuration to run your tests using Puppeteer. - -1. First install `jest-puppeteer-preset` - -``` -yarn add --dev jest-puppeteer-preset -``` - -2. Specify preset in your Jest configuration: - -```json -{ - "preset": "jest-puppeteer-preset" -} -``` - -See [documentation](https://github.com/smooth-code/jest-puppeteer). - -## Custom example - -The basic idea is to: - -1. launch & file the websocket endpoint of puppeteer with Global Setup -2. connect to puppeteer from each Test Environment -3. close puppeteer with Global Teardown - -Here's an example of the GlobalSetup script - -```js -// setup.js -module.exports = async function() { - const browser = await puppeteer.launch(); - // store the browser instance so we can teardown it later - global.__BROWSER__ = browser; - - // file the wsEndpoint for TestEnvironments - mkdirp.sync(DIR); - fs.writeFileSync(path.join(DIR, 'wsEndpoint'), browser.wsEndpoint()); -}; -``` - -Then we need a custom Test Environment for puppeteer - -```js -// puppeteer_environment.js -class PuppeteerEnvironment extends NodeEnvironment { - constructor(config) { - super(config); - } - - async setup() { - await super.setup(); - // get the wsEndpoint - const wsEndpoint = fs.readFileSync(path.join(DIR, 'wsEndpoint'), 'utf8'); - if (!wsEndpoint) { - throw new Error('wsEndpoint not found'); - } - - // connect to puppeteer - this.global.__BROWSER__ = await puppeteer.connect({ - browserWSEndpoint: wsEndpoint, - }); - } - - async teardown() { - await super.teardown(); - } - - runScript(script) { - return super.runScript(script); - } -} -``` - -Finally we can close the puppeteer instance and clean-up the file - -```js -// teardown.js -module.exports = async function() { - // close the browser instance - await global.__BROWSER__.close(); - - // clean-up the wsEndpoint file - rimraf.sync(DIR); -}; -``` - -With all the things set up, we can now write our tests like this: - -```js -// test.js -describe( - '/ (Home Page)', - () => { - let page; - beforeAll(async () => { - page = await global.__BROWSER__.newPage(); - await page.goto('https://google.com'); - }, timeout); - - it('should load without error', async () => { - const text = await page.evaluate(() => document.body.textContent); - expect(text).toContain('google'); - }); - }, - timeout, -); -``` - -Here's the code of -[full working example](https://github.com/xfumihiro/jest-puppeteer-example). diff --git a/website/versioned_docs/version-22.4/TestingFrameworks.md b/website/versioned_docs/version-22.4/TestingFrameworks.md deleted file mode 100644 index a1104690a19b..000000000000 --- a/website/versioned_docs/version-22.4/TestingFrameworks.md +++ /dev/null @@ -1,38 +0,0 @@ ---- -id: version-22.4-testing-frameworks -title: Testing Web Frameworks -original_id: testing-frameworks ---- - -Although Jest may be considered a React-specific test runner, in fact it is a -universal testing platform, with the ability to adapt to any JavaScript library -or framework. In this section we'd like to link to community posts and articles -about integrating Jest into other popular JS libraries. - -## Vue.js - -* [Testing Vue.js components with Jest](https://alexjoverm.github.io/series/Unit-Testing-Vue-js-Components-with-the-Official-Vue-Testing-Tools-and-Jest/) - by Alex Jover Morales ([@alexjoverm](https://twitter.com/alexjoverm)) -* [Jest for all: Episode 1 — Vue.js](https://medium.com/@kentaromiura_the_js_guy/jest-for-all-episode-1-vue-js-d616bccbe186#.d573vrce2) - by Cristian Carlesso ([@kentaromiura](https://twitter.com/kentaromiura)) - -## AngularJS - -* [Testing an AngularJS app with Jest](https://medium.com/aya-experience/testing-an-angularjs-app-with-jest-3029a613251) - by Matthieu Lux ([@Swiip](https://twitter.com/Swiip)) -* [Running AngularJS Tests with Jest](https://engineering.talentpair.com/running-angularjs-tests-with-jest-49d0cc9c6d26) - by Ben Brandt ([@benjaminbrandt](https://twitter.com/benjaminbrandt)) - -## Angular - -* [Testing Angular faster with Jest](https://www.xfive.co/blog/testing-angular-faster-jest/) - by Michał Pierzchała ([@thymikee](https://twitter.com/thymikee)) - -## MobX - -* [How to Test React and MobX with Jest](https://semaphoreci.com/community/tutorials/how-to-test-react-and-mobx-with-jest) - by Will Stern ([@willsterndev](https://twitter.com/willsterndev)) - -## Redux - -* [Writing Tests](https://redux.js.org/recipes/writing-tests) by Redux docs diff --git a/website/versioned_docs/version-22.4/TutorialReact.md b/website/versioned_docs/version-22.4/TutorialReact.md index 5b8f4ace8171..fe41d813cca5 100644 --- a/website/versioned_docs/version-22.4/TutorialReact.md +++ b/website/versioned_docs/version-22.4/TutorialReact.md @@ -312,7 +312,8 @@ module.exports = { return babel.transform(src, { filename, presets: [jestPreset], - }); + retainLines: true, + }).code; } return src; }, diff --git a/website/versioned_sidebars/version-22.4-sidebars.json b/website/versioned_sidebars/version-22.4-sidebars.json deleted file mode 100644 index 0fb00ab55d8a..000000000000 --- a/website/versioned_sidebars/version-22.4-sidebars.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "version-22.4-docs": { - "Introduction": [ - "version-22.4-getting-started", - "version-22.4-using-matchers", - "version-22.4-asynchronous", - "version-22.4-setup-teardown", - "version-22.4-mock-functions", - "version-22.4-jest-platform", - "version-22.4-jest-community", - "version-22.4-more-resources" - ], - "Guides": [ - "version-22.4-snapshot-testing", - "version-22.4-tutorial-async", - "version-22.4-timer-mocks", - "version-22.4-manual-mocks", - "version-22.4-es6-class-mocks", - "version-22.4-webpack", - "version-22.4-puppeteer", - "version-22.4-mongodb", - "version-22.4-migration-guide", - "version-22.4-troubleshooting" - ], - "Framework Guides": [ - "version-22.4-tutorial-react", - "version-22.4-tutorial-react-native", - "version-22.4-testing-frameworks" - ], - "API Reference": [ - "version-22.4-api", - "version-22.4-expect", - "version-22.4-mock-function-api", - "version-22.4-jest-object", - "version-22.4-configuration", - "version-22.4-cli" - ] - } -}