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

sw-order-customer-grid.spec.ts ➔ createWrapper   B

Complexity

Conditions 2

Size

Total Lines 69
Code Lines 50

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 50
dl 0
loc 69
rs 8.6363
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 { shallowMount, createLocalVue } from '@vue/test-utils';
4
import type { Wrapper } from '@vue/test-utils';
5
import swOrderCustomerGrid from 'src/module/sw-order/component/sw-order-customer-grid';
6
import 'src/app/component/entity/sw-entity-listing';
7
import 'src/app/component/data-grid/sw-data-grid';
8
import 'src/app/component/grid/sw-pagination';
9
import orderState from 'src/module/sw-order/state/order.store';
10
11
Shopware.Component.register('sw-order-customer-grid', swOrderCustomerGrid);
12
13
let customerData = [];
14
15
function setCustomerData(customers) {
16
    customerData = [...customers];
17
    customerData.total = customers.length;
18
    customerData.criteria = {
19
        page: 1,
20
        limit: 5
21
    };
22
}
23
24
const customers = generateCustomers();
25
26
function generateCustomers() {
27
    const items = [];
28
29
    for (let i = 1; i <= 10; i += 1) {
30
        items.push({
31
            id: i,
32
            firstName: `Quynh ${i}`,
33
            lastName: 'Nguyen',
34
            email: `quynh${i}@example.com`,
35
            salesChannelId: '1234',
36
            customerNumber: i,
37
            salesChannel: {
38
                translated: {
39
                    name: 'Storefront'
40
                }
41
            }
42
        });
43
    }
44
45
    return items;
46
}
47
48
async function createWrapper(): Promise<Wrapper<Vue>> {
49
    const localVue = createLocalVue();
50
    localVue.use(Vuex);
51
    localVue.filter('currency', v => v);
52
53
    return shallowMount(await Shopware.Component.build('sw-order-customer-grid'), {
54
        localVue,
55
        stubs: {
56
            'sw-card': {
57
                template: `
58
                    <div class="sw-card__content">
59
                         <slot name="toolbar"></slot>
60
                        <slot name="grid"></slot>
61
                    </div>
62
                `
63
            },
64
            'sw-number-field': {
65
                template: '<input class="sw-number-field" type="number" v-model="value" />',
66
                props: {
67
                    value: 0
68
                }
69
            },
70
            'sw-checkbox-field': {
71
                template: '<input class="sw-checkbox-field" type="checkbox" v-model="value" />',
72
                props: {
73
                    value: false
74
                }
75
            },
76
            'sw-entity-listing': await Shopware.Component.build('sw-entity-listing'),
77
            'sw-data-grid': await Shopware.Component.build('sw-data-grid'),
78
            'sw-pagination': await Shopware.Component.build('sw-pagination'),
79
            'sw-product-variant-info': true,
80
            'sw-data-grid-settings': true,
81
            'sw-data-grid-skeleton': true,
82
            'sw-context-button': {
83
                template: '<div class="sw-context-button"><slot></slot></div>'
84
            },
85
            'sw-context-menu-item': true,
86
            'sw-empty-state': true,
87
            'sw-card-filter': {
88
                props: ['value'],
89
                template: '<input class="sw-card-filter" :value="value" @input="$emit(\'sw-card-filter-term-change\', $event.target.value)">'
90
            },
91
            'sw-icon': true,
92
            'sw-field': true,
93
            'router-link': true,
94
            'sw-button': {
95
                template: '<button @click="$emit(\'click\', $event)"><slot></slot></button>'
96
            },
97
            'sw-order-new-customer-modal': true,
98
        },
99
        provide: {
100
            searchRankingService: () => {},
101
            repositoryFactory: {
102
                create: () => {
103
                    return {
104
                        search: () => Promise.resolve(customerData),
105
                        get: () => Promise.resolve({ ...customers[0] }),
106
                    };
107
                }
108
            }
109
        },
110
        mocks: {
111
            $tc: (key, number, value) => {
112
                if (!value) {
113
                    return key;
114
                }
115
                return key + JSON.stringify(value);
116
            }
117
        },
118
    });
119
}
120
121
122
describe('src/module/sw-order/view/sw-order-customer-grid', () => {
123
    beforeAll(() => {
124
        Shopware.Service().register('contextStoreService', () => {
125
            return {
126
                updateCustomerContext: () => Promise.resolve({
127
                    status: 200
128
                }),
129
            };
130
        });
131
132
        Shopware.Service().register('cartStoreService', () => {
133
            return {
134
                getCart: () => Promise.resolve({
135
                    data: {
136
                        token: 'token',
137
                        lineItems: []
138
                    }
139
                }),
140
                createCart: () => Promise.resolve({
141
                    data: {
142
                        token: 'token',
143
                    }
144
                }),
145
            };
146
        });
147
148
        Shopware.State.registerModule('swOrder', {
149
            ...orderState,
150
            state: {
151
                cart: {
152
                    token: '',
153
                    lineItems: [],
154
                },
155
                context: {
156
                    customer: {},
157
                },
158
            }
159
        });
160
    });
161
162
    it('should show empty state view when there is no customer', async () => {
163
        setCustomerData([]);
164
165
        const wrapper = await createWrapper();
166
        await flushPromises();
167
168
        const emptyState = wrapper.find('sw-empty-state-stub');
169
        expect(emptyState.exists()).toBeTruthy();
170
    });
171
172
    it('should show empty title correctly', async () => {
173
        setCustomerData([]);
174
175
        const wrapper = await createWrapper();
176
        await flushPromises();
177
178
        let emptyState = wrapper.find('sw-empty-state-stub');
179
        expect(emptyState.attributes('title')).toEqual('sw-customer.list.messageEmpty');
180
181
        const searchField = wrapper.find('.sw-card-filter');
182
183
        await searchField.setValue('Hello World');
184
        await searchField.trigger('input');
185
186
        emptyState = wrapper.find('sw-empty-state-stub');
187
        expect(emptyState.attributes('title'))
188
            .toEqual('sw-order.initialModal.customerGrid.textEmptySearch{"name":"Hello World"}');
189
    });
190
191
    it('should show customer grid', async () => {
192
        setCustomerData(customers);
193
194
        const wrapper = await createWrapper();
195
        await flushPromises();
196
197
        const emptyState = wrapper.find('sw-empty-state-stub');
198
        expect(emptyState.exists()).toBeFalsy();
199
200
        const gridBody = wrapper.find('.sw-data-grid__body');
201
        expect(gridBody.findAll('.sw-data-grid__row').length).toEqual(customers.length);
202
    });
203
204
    it('should able to search customer', async () => {
205
        setCustomerData(customers);
206
207
        const wrapper = await createWrapper();
208
        await flushPromises();
209
210
        let gridBody = wrapper.find('.sw-data-grid__body');
211
        expect(gridBody.findAll('.sw-data-grid__row').length).toEqual(customers.length);
212
213
        setCustomerData([{ ...customers[1] }]);
214
        const searchField = wrapper.find('.sw-card-filter');
215
216
        await searchField.setValue('Quynh 2');
217
        await searchField.trigger('input');
218
219
        gridBody = wrapper.find('.sw-data-grid__body');
220
        expect(gridBody.findAll('.sw-data-grid__row').length).toEqual(1);
221
    });
222
223
    it('should open add new customer modal', async () => {
224
        setCustomerData([]);
225
226
        const wrapper = await createWrapper();
227
        await flushPromises();
228
229
        const buttonAddCustomer = wrapper.find('.sw-order-customer-grid__add-customer');
230
        let modalAddCustomer = wrapper.find('sw-order-new-customer-modal-stub');
231
232
        expect(modalAddCustomer.exists()).toBeFalsy();
233
234
        await buttonAddCustomer.trigger('click');
235
236
        modalAddCustomer = wrapper.find('sw-order-new-customer-modal-stub');
237
        expect(modalAddCustomer.exists()).toBeTruthy();
238
    });
239
240
    it('should refresh grid list after adding new customer successfully', async () => {
241
        setCustomerData([]);
242
243
        const wrapper = await createWrapper();
244
        await flushPromises();
245
246
        const spyGetList = jest.spyOn(wrapper.vm, 'getList');
247
        const buttonAddCustomer = wrapper.find('.sw-order-customer-grid__add-customer');
248
        await buttonAddCustomer.trigger('click');
249
250
        const modalAddCustomer = wrapper.find('sw-order-new-customer-modal-stub');
251
        modalAddCustomer.vm.$emit('on-select-existing-customer', 'customer1');
252
253
        expect(spyGetList).toHaveBeenCalled();
254
    });
255
256
    it('should create cart after selecting a customer if there is no cart token', async () => {
257
        setCustomerData(customers);
258
259
        const wrapper = await createWrapper();
260
        await flushPromises();
261
262
        const spyCreateCart = jest.spyOn(wrapper.vm, 'createCart');
263
264
        const firstRow = wrapper.find('.sw-data-grid__body .sw-data-grid__row--0');
265
        await firstRow.find('.sw-field__radio-input input').setChecked(true);
266
267
        await flushPromises();
268
269
        expect(spyCreateCart).toHaveBeenCalled();
270
    });
271
272
    it('should update customer context and cart after selecting a customer', async () => {
273
        setCustomerData(customers);
274
        Shopware.State.commit('swOrder/setCartToken', 'token');
275
276
        const wrapper = await createWrapper();
277
        await flushPromises();
278
279
        wrapper.vm.customerRepository.get = jest.fn(() => Promise.resolve(customers[0]));
280
        const spyUpdateCustomerContext = jest.spyOn(wrapper.vm, 'updateCustomerContext');
281
        const spyGetCart = jest.spyOn(wrapper.vm, 'getCart');
282
283
        const firstRow = wrapper.find('.sw-data-grid__body .sw-data-grid__row--0');
284
        await firstRow.find('.sw-field__radio-input input').setChecked(true);
285
286
        expect(spyUpdateCustomerContext).toHaveBeenCalled();
287
288
        await flushPromises();
289
290
        expect(spyGetCart).toHaveBeenCalled();
291
    });
292
293
    it('should check customer initially if customer exists', async () => {
294
        setCustomerData(customers);
295
296
        Shopware.State.commit('swOrder/setCustomer', {
297
            ...customers[0],
298
        });
299
300
        const wrapper = await createWrapper();
301
302
        const firstRow = wrapper.find('.sw-data-grid__body .sw-data-grid__row--0');
303
        const firstRowRadioField = firstRow.find('.sw-field__radio-input input');
304
305
        await flushPromises();
306
307
        expect(firstRowRadioField.element.checked).toBeTruthy();
308
    });
309
});
310