Passed
Push — 6.4 ( a2ab34...70d76f )
by Christian
13:23 queued 14s
created

sw-order-create-options.spec.ts ➔ createWrapper   B

Complexity

Conditions 4

Size

Total Lines 87
Code Lines 58

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 58
dl 0
loc 87
rs 8.3745
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
import Vue from 'vue';
2
import Vuex from 'vuex';
3
import { createLocalVue, shallowMount } from '@vue/test-utils';
4
import type { Wrapper } from '@vue/test-utils';
5
6
import EntityCollection from 'src/core/data/entity-collection.data';
7
import orderStore from 'src/module/sw-order/state/order.store';
8
import swOrderCreateOptions from 'src/module/sw-order/component/sw-order-create-options';
9
import swOrderCustomerAddressSelect from 'src/module/sw-order/component/sw-order-customer-address-select';
10
import 'src/module/sw-order/mixin/cart-notification.mixin';
11
12
import 'src/app/component/form/select/base/sw-single-select';
13
import 'src/app/component/form/field-base/sw-base-field';
14
import 'src/app/component/form/field-base/sw-block-field';
15
import 'src/app/component/form/sw-switch-field';
16
import 'src/app/component/form/sw-checkbox-field';
17
import 'src/app/component/form/select/base/sw-select-base';
18
import 'src/app/component/form/select/base/sw-select-result-list';
19
20
const addresses = [
21
    {
22
        id: '1',
23
        city: 'San Francisco',
24
        zipcode: '10332',
25
        street: 'Summerfield 27',
26
        country: {
27
            translated: {
28
                name: 'USA'
29
            }
30
        },
31
        countryState: {
32
            translated: {
33
                name: 'California'
34
            }
35
        }
36
    },
37
    {
38
        id: '2',
39
        city: 'London',
40
        zipcode: '48624',
41
        street: 'Ebbinghoff 10',
42
        country: {
43
            translated: {
44
                name: 'United Kingdom'
45
            }
46
        },
47
        countryState: {
48
            translated: {
49
                name: 'Nottingham'
50
            }
51
        }
52
    },
53
];
54
55
const customerData = {
56
    id: '123',
57
    salesChannel: {
58
        languageId: 'english'
59
    },
60
    billingAddressId: '1',
61
    shippingAddressId: '2',
62
    addresses: new EntityCollection(
63
        '/customer-address',
64
        'customer-address',
65
        null,
66
        null,
67
        [],
68
    ),
69
};
70
71
const context = {
72
    salesChannel: {
73
        id: '1',
74
    },
75
    customer: {
76
        ...customerData
77
    },
78
    currency: {
79
        shortName: 'EUR',
80
        symbol: '€',
81
        totalRounding: {
82
            decimals: 2,
83
        },
84
    },
85
};
86
87
const cart = {
88
    token: '',
89
    deliveries: [],
90
    lineItems: [],
91
};
92
93
const cartResponse = {
94
    data: cart,
95
};
96
97
const contextResponse = {
98
    data: {
99
        ...context,
100
        currency: {
101
            id: '1',
102
            shortName: 'USD',
103
            symbol: '$',
104
            totalRounding: {
105
                decimals: 2,
106
            },
107
        },
108
    },
109
};
110
111
Shopware.Component.register('sw-order-create-options', swOrderCreateOptions);
112
Shopware.Component.register('sw-order-customer-address-select', swOrderCustomerAddressSelect);
113
114
async function createWrapper(): Promise<Wrapper<Vue>> {
115
    const localVue = createLocalVue();
116
    localVue.use(Vuex);
117
118
    return shallowMount(await Shopware.Component.build('sw-order-create-options'), {
119
        localVue,
120
        propsData: {
121
            promotionCodes: [],
122
            disabledAutoPromotion: false,
123
            context: {
124
                languageId: 'english',
125
                billingAddressId: '1',
126
                shippingAddressId: '2',
127
            },
128
        },
129
        provide: {
130
            repositoryFactory: {
131
                create: () => {
132
                    return {
133
                        search: () => Promise.resolve(addresses),
134
                    };
135
                }
136
            },
137
        },
138
        stubs: {
139
            'sw-container': {
140
                template: '<div class="sw-container"><slot></slot></div>'
141
            },
142
            'sw-popover': {
143
                template: '<div class="sw-popover"><slot></slot></div>'
144
            },
145
            'sw-single-select': await Shopware.Component.build('sw-single-select'),
146
            'sw-select-result-list': await Shopware.Component.build('sw-select-result-list'),
147
            'sw-select-base': await Shopware.Component.build('sw-select-base'),
148
            'sw-block-field': await Shopware.Component.build('sw-block-field'),
149
            'sw-base-field': await Shopware.Component.build('sw-base-field'),
150
            'sw-order-customer-address-select': await Shopware.Component.build('sw-order-customer-address-select'),
151
            'sw-switch-field': await Shopware.Component.build('sw-switch-field'),
152
            'sw-text-field': true,
153
            'sw-entity-single-select': {
154
                props: ['value'],
155
                template: '<input class="sw-entity-single-select" :value="value" @input="$emit(\'input\', $event.target.value)">'
156
            },
157
            'sw-multi-tag-select': {
158
                props: ['value', 'validate'],
159
                template: `
160
                    <div class="sw-multi-tag-select">
161
                        <ul>
162
                            <li v-for="item in value">{{ item }}</li>
163
                        </ul>
164
                        <input @input="updateTags">
165
                    </div>
166
                `,
167
                methods: {
168
                    updateTags(event) {
169
                        if (!this.validate(event.target.value)) {
170
                            return;
171
                        }
172
173
                        this.$emit('change', [...this.value, event.target.value]);
174
                    },
175
                },
176
            },
177
            'sw-highlight-text': true,
178
            'sw-loader': true,
179
            'sw-icon': true,
180
            'sw-field-error': true,
181
            'sw-number-field': {
182
                template: `
183
                    <div class="sw-number-field">
184
                        <input type="number" :value="value" @input="$emit('change', Number($event.target.value))" />
185
                        <slot name="suffix"></slot>
186
                    </div>
187
                `,
188
                props: {
189
                    value: 0
190
                }
191
            },
192
            'sw-select-result': {
193
                props: ['item', 'index'],
194
                template: `<li class="sw-select-result" @click.stop="onClickResult">
195
                                <slot></slot>
196
                           </li>`,
197
                methods: {
198
                    onClickResult() {
199
                        this.$parent.$parent.$emit('item-select', this.item);
200
                    }
201
                }
202
            },
203
        },
204
    });
205
}
206
207
describe('src/module/sw-order/view/sw-order-create-options', () => {
208
    beforeAll(() => {
209
        Shopware.Service().register('contextStoreService', () => {
210
            return {
211
                updateContext: () => Promise.resolve({}),
212
                getSalesChannelContext: () => Promise.resolve(contextResponse),
213
            };
214
        });
215
216
        Shopware.Service().register('cartStoreService', () => {
217
            return {
218
                getCart: () => Promise.resolve(cartResponse)
219
            };
220
        });
221
222
        Shopware.State.registerModule('swOrder', {
223
            ...orderStore,
224
            state: {
225
                ...orderStore.state,
226
                customer: {
227
                    ...customerData
228
                },
229
                cart,
230
                context,
231
            },
232
        });
233
    });
234
235
    it('should show address option correctly', async () => {
236
        const wrapper = await createWrapper();
237
        await flushPromises();
238
239
        const billingAddressSelect = wrapper.find('.sw-order-create-options__billing-address .sw-select__selection');
240
        // Click to open result list
241
        await billingAddressSelect.trigger('click');
242
243
        expect(wrapper.find('li[selected="selected"]').text()).toEqual('Summerfield 27, 10332, San Francisco, California, USA');
244
        expect(wrapper.find('sw-highlight-text-stub').attributes().text).toEqual('Ebbinghoff 10, 48624, London, Nottingham, United Kingdom');
245
    });
246
247
248
    it('should able to set shipping address same as billing address', async () => {
249
        const wrapper = await createWrapper();
250
        await flushPromises();
251
252
        let shippingSelectionText = wrapper.find('.sw-order-create-options__shipping-address .sw-single-select__selection-text');
253
        expect(shippingSelectionText.text()).toEqual('Ebbinghoff 10, 48624, London, Nottingham, United Kingdom');
254
255
        const switchSameAddress = wrapper.find('.sw-field--switch__input input[name="sw-field--isSameAsBillingAddress"]');
256
        await switchSameAddress.setChecked(true);
257
258
        expect(wrapper.vm.context.shippingAddressId).toBe('1');
259
260
        shippingSelectionText = wrapper.find('.sw-order-create-options__shipping-address .sw-single-select__selection-text');
261
        expect(shippingSelectionText.text())
262
            .toEqual('sw-order.initialModal.options.textSameAsBillingAddress');
263
264
        expect(wrapper.find('.sw-order-create-options__shipping-address')
265
            .attributes('disabled')).toBeTruthy();
266
    });
267
268
    it('should disable shipping address when toggle on same as billing address switch', async () => {
269
        const wrapper = await createWrapper();
270
        await flushPromises();
271
272
        const switchSameAddress = wrapper.find('.sw-field--switch__input input[name="sw-field--isSameAsBillingAddress"]');
273
        expect(switchSameAddress.element.checked).toBeFalsy();
274
275
        await switchSameAddress.setChecked(true);
276
277
        expect(wrapper.find('.sw-order-create-options__shipping-address')
278
            .attributes('disabled')).toBeTruthy();
279
    });
280
281
    it('should enable shipping address when toggle on same as billing address switch', async () => {
282
        const wrapper = await createWrapper();
283
        await flushPromises();
284
285
        await wrapper.setProps({
286
            context: {
287
                languageId: 'english',
288
                billingAddressId: '1',
289
                shippingAddressId: '1',
290
            },
291
        });
292
293
        const switchSameAddress = wrapper.find('.sw-field--switch__input input[name="sw-field--isSameAsBillingAddress"]');
294
        expect(switchSameAddress.element.checked).toBeTruthy();
295
296
297
        await switchSameAddress.setChecked(false);
298
299
        expect(wrapper.find('.sw-order-create-options__shipping-address')
300
            .attributes('disabled')).toBeUndefined();
301
    });
302
303
    it('should switch on same as billing toogle when selecting billing address the same as shipping address', async () => {
304
        const wrapper = await createWrapper();
305
        await flushPromises();
306
307
        let shippingSelectionText = wrapper.find('.sw-order-create-options__shipping-address .sw-single-select__selection-text');
308
        expect(shippingSelectionText.text()).toEqual('Ebbinghoff 10, 48624, London, Nottingham, United Kingdom');
309
310
        const billingAddressSelect = wrapper.find('.sw-order-create-options__billing-address .sw-select__selection');
311
        // Click to open result list
312
        await billingAddressSelect.trigger('click');
313
314
        const addressOptions = wrapper.findAll('.sw-select-result');
315
        await addressOptions.at(1).trigger('click');
316
317
        shippingSelectionText = wrapper.find('.sw-order-create-options__shipping-address .sw-single-select__selection-text');
318
        expect(shippingSelectionText.text()).toEqual('sw-order.initialModal.options.textSameAsBillingAddress');
319
320
        expect(wrapper.vm.context.billingAddressId).toBe('2');
321
    });
322
323
    it('should emit auto-promotion-toggle when toggling disable auto promotion', async () => {
324
        const wrapper = await createWrapper();
325
326
        const disableAutoPromotionSwitch = wrapper.find('.sw-order-create-options__disable-auto-promotion input');
327
        await disableAutoPromotionSwitch.setChecked(true);
328
329
        expect(wrapper.emitted('auto-promotion-toggle')).toBeTruthy();
330
        expect(wrapper.emitted('auto-promotion-toggle')[0][0]).toBeTruthy();
331
    });
332
333
    it('should able to select currency', async () => {
334
        const wrapper = await createWrapper();
335
336
        let shippingCostField = wrapper.find('.sw-order-create-options__shipping-cost');
337
        expect(shippingCostField.text()).toEqual('€');
338
339
        const currencyInput = wrapper.find('.sw-order-create-options__currency-select');
340
        await currencyInput.trigger('input');
341
        await flushPromises();
342
343
        shippingCostField = wrapper.find('.sw-order-create-options__shipping-cost');
344
        expect(shippingCostField.text()).toEqual('$');
345
    });
346
347
    it('should emit shipping-cost-change event when edit shipping cost field', async () => {
348
        const wrapper = await createWrapper();
349
350
        const shippingCostField = wrapper.find('.sw-order-create-options__shipping-cost input');
351
        await shippingCostField.setValue(100);
352
        await shippingCostField.trigger('input');
353
354
        expect(wrapper.emitted('shipping-cost-change')).toBeTruthy();
355
        expect(wrapper.emitted('shipping-cost-change')[0][0]).toEqual(100);
356
    });
357
358
    it('should emit promotions-change event when adding a promotion code', async () => {
359
        const wrapper = await createWrapper();
360
361
        const promotionField = wrapper.find('.sw-order-create-options__promotion-code input');
362
        await promotionField.setValue('DISCOUNT');
363
        await promotionField.trigger('input');
364
365
        expect(wrapper.emitted('promotions-change')).toBeTruthy();
366
        expect(wrapper.emitted('promotions-change')[0][0]).toEqual(['DISCOUNT']);
367
    });
368
369
    it('should not emit promotions-change event when entering duplicated promotion code', async () => {
370
        const wrapper = await createWrapper();
371
372
        await wrapper.setProps({
373
            promotionCodes: ['DISCOUNT']
374
        });
375
376
        const promotionField = wrapper.find('.sw-order-create-options__promotion-code input');
377
        await promotionField.setValue('DISCOUNT');
378
        await promotionField.trigger('input');
379
380
        expect(wrapper.emitted('promotions-change')).toBeFalsy();
381
    });
382
383
    it('should not emit promotions-change event when entering empty promotion code', async () => {
384
        const wrapper = await createWrapper();
385
386
        const promotionField = wrapper.find('.sw-order-create-options__promotion-code input');
387
        await promotionField.setValue('     ');
388
        await promotionField.trigger('input');
389
390
        expect(wrapper.emitted('promotions-change')).toBeFalsy();
391
    });
392
393
    it('should update context when selecting shipping method', async () => {
394
        const wrapper = await createWrapper();
395
396
        const shippingCostField = wrapper.find('.sw-order-create-options__shipping-cost input');
397
        expect(shippingCostField.element.value).toEqual('0');
398
399
        Shopware.Service('cartStoreService').getCart = jest.fn(() => Promise.resolve({
400
            data: {
401
                lineItems: [],
402
                deliveries: [{
403
                    shippingCosts: {
404
                        totalPrice: 100,
405
                    },
406
                }],
407
            },
408
        }));
409
410
        const shippingMethodSelect = wrapper.find('.sw-order-create-options__shipping-method');
411
        await shippingMethodSelect.trigger('input');
412
        await flushPromises();
413
414
        expect(shippingCostField.element.value).toEqual('100');
415
    });
416
});
417