|
1 |
| -Can we mock an import used in the component under test? |
2 |
| - |
3 |
| -See [sinon.js discussion](https://github.com/sinonjs/sinon/issues/1121) |
4 |
| - |
5 |
| -## Solution |
6 |
| - |
7 |
| -In babel configuration file, add one more plugin |
8 |
| - |
9 |
| -```js |
10 |
| -// https://babeljs.io/docs/en/babel-plugin-transform-modules-commonjs |
11 |
| -// loose ES6 modules allow us to dynamically mock imports during tests |
12 |
| -;[ |
13 |
| - '@babel/plugin-transform-modules-commonjs', |
14 |
| - { |
15 |
| - loose: true, |
16 |
| - }, |
17 |
| -] |
18 |
| -``` |
19 |
| - |
20 |
| -The ES6 exports and imports then will be a plain object then |
21 |
| - |
22 |
| -```js |
23 |
| -// when loose: true |
24 |
| -// each ES6 export is made using plain objet |
25 |
| -var exports = { foo: 'bar' } |
26 |
| -// which we can overwrite later |
27 |
| - |
28 |
| -// when loose: false |
29 |
| -// each ES6 export is made using |
30 |
| -// Object.defineProperty(exports, { value: ..., configurable: false }) |
31 |
| -// which we cannot change |
32 |
| -``` |
33 |
| - |
34 |
| -We can overwrite a property like this |
35 |
| - |
36 |
| -```js |
37 |
| -// component imports and uses greeting |
38 |
| -// like this |
39 |
| -// import {greeting} from './greeting' |
40 |
| -import Component from './component' |
41 |
| -import * as GreetingModule from './greeting' |
42 |
| -it('shows mock greeting', () => { |
43 |
| - // stub property on the loaded ES6 module using cy.stub |
44 |
| - // which will be restored after the test automatically |
45 |
| - cy.stub(GreetingModule, 'greeting', 'test greeting') |
46 |
| - mount(<Component />) |
47 |
| - cy.contains('h1', 'test greeting').should('be.visible') |
48 |
| -}) |
49 |
| -``` |
50 |
| - |
51 |
| -## PizzaProps |
52 |
| - |
53 |
| -If the component is using `defaultProps` to pass a method to call, you can stub it, see [PizzaProps.js](PizzaProps.js) and [PizzaProps.spec.js](PizzaProps.spec.js) |
54 |
| - |
55 |
| -```js |
56 |
| -import PizzaProps from './PizzaProps' |
57 |
| -cy.stub(PizzaProps.defaultProps, 'fetchIngredients').resolves(...) |
58 |
| -``` |
59 |
| - |
60 |
| -## RemotePizza |
61 |
| - |
62 |
| -Even if the import is renamed, you can stub using the original name, see [RemotePizza.js](RemotePizza.js) and [RemotePizza.spec.js](RemotePizza.spec.js) |
63 |
| - |
64 |
| -```js |
65 |
| -// RemotePizza.js |
66 |
| -import { fetchIngredients as defaultFetchIngredients } from './services' |
67 |
| -// RemotePizza.spec.js |
68 |
| -import * as services from './services' |
69 |
| -cy.stub(services, 'fetchIngredients').resolves(...) |
70 |
| -``` |
| 1 | +## Mocking imports |
0 commit comments