Best JavaScript code snippet using devicefarmer-stf
index.js
Source:index.js  
1import { CloseOutlined, LinkOutlined, SaveOutlined } from "@ant-design/icons"2import { Button, Col, Form, notification, Row, Space } from "antd"3import BreadcrumbField from "Components/Admin/CustomFields/BreadcrumbField"4import InputField from "Components/Admin/CustomFields/InputField"5import SelectField from "Components/Admin/CustomFields/SelectField"6import { LIST_RENDER_DEFAULT, TYPE_CUSTOM_FIELD } from "Constants/Data"7import { VALIDATE_MESSAGES } from "Constants/Validate"8import { useEffect, useState } from "react"9import { useDispatch, useSelector } from "react-redux"10import { useHistory } from "react-router-dom"11import {12    setIsSSDForCreateDrive,13    setProductTypeIdForCreate14} from "Redux/Admin/Product/ProductAdmin.reducer"15import {16    createProductsApi,17    getSpecListApi18} from "Redux/Admin/Product/ProductAdmin.thunk"19import "../AddEditPage.css"20const layout = {21    labelCol: { span: 8 },22    wrapperCol: { span: 12 }23}24const AddProductPage = () => {25    const dispatch = useDispatch()26    const history = useHistory()27    const [indexForm, setIndexForm] = useState(1)28    const filterAll = useSelector(state => state.ProductAdminReducer.filterAll)29    const productTypeIdForCreate = useSelector(30        state => state.ProductAdminReducer.productTypeIdForCreate31    )32    const isSSDForCreateDrive = useSelector(33        state => state.ProductAdminReducer.isSSDForCreateDrive34    )35    const [cancel, setCancel] = useState(false)36    //----------------------GET DATA SHOW SELECT FIELDS----------37    useEffect(() => {38        dispatch(getSpecListApi())39    }, [])40    //----------------------RELOAD FORM---------------------------41    useEffect(() => {42        setIndexForm(indexForm + 1)43    }, [productTypeIdForCreate])44    //------------------------NOTIFY-----------------------------45    const openNotify = (type, title, message) => {46        notification[type]({47            message: title,48            description: message49        })50    }51    //------------------------SUBMIT------------------------------52    const onCancel = () => {53        setCancel(true)54        history.push("/admin/home")55    }56    const onFinish = values => {57        if (!cancel) {58            if (productTypeIdForCreate === 1) {59                const bodyLaptop = {60                    info: {61                        name: values.name,62                        description: values.description,63                        guarantee: Number(values.guarantee),64                        price: Number(values.price),65                        brand_id: Number(values.brand_id),66                        type_id: Number(values.type_id)67                    },68                    spec: {69                        cpu_id: Number(values.cpu_id),70                        gpu_id: Number(values.gpu_id),71                        ram_id: Number(values.ram_id),72                        size_id: Number(values.size_id),73                        rom_id: Number(values.rom_id),74                        screen_id: Number(values.screen_id),75                        port_id: Number(values.port_id),76                        os_id: Number(values.os_id),77                        battery_id: Number(values.battery_id),78                        weight_id: Number(values.weight_id)79                    },80                    images: {81                        img1: values.img1,82                        img2: values.img2,83                        img3: values.img384                    }85                }86                dispatch(createProductsApi("laptop", bodyLaptop)).then(notify =>87                    openNotify(notify.type, notify.title, notify.message)88                )89            }90            if (productTypeIdForCreate === 2) {91                const bodyDrive = {92                    info: {93                        name: values.name,94                        description: values.description,95                        guarantee: Number(values.guarantee),96                        price: Number(values.price),97                        brand_id: Number(values.brand_id),98                        type_id: Number(values.type_id)99                    },100                    spec: {101                        capacity_id: Number(values.capacity_id),102                        cache_id: isSSDForCreateDrive103                            ? 1104                            : Number(values.cache_id),105                        connect_id: Number(values.connect_id),106                        write_id: Number(values.write_id),107                        read_id: Number(values.read_id),108                        dimension_id: Number(values.dimension_id),109                        rotation_id: isSSDForCreateDrive110                            ? 1111                            : Number(values.rotation_id),112                        drive_type_id: Number(values.drive_type_id)113                    },114                    image: {115                        img1: values.img1,116                        img2: values.img2,117                        img3: values.img3118                    }119                }120                dispatch(createProductsApi("drive", bodyDrive)).then(notify =>121                    openNotify(notify.type, notify.title, notify.message)122                )123            } else {124                openNotify(125                    "info",126                    "Thêm chưa thành công!",127                    "TÃnh nÄng Äang cáºp nháºt"128                )129            }130        }131    }132    //------------------------COMPONENT RENDER---------------------133    const renderSpecLaptop = () => {134        return (135            <Col span={12}>136                <SelectField137                    name={"cpu_id"}138                    label={"Vi xá» lÃ"}139                    options={140                        (filterAll && filterAll.laptop.cpus) ||141                        LIST_RENDER_DEFAULT142                    }143                    rules={[{ required: true }]}144                />145                <SelectField146                    name={"ram_id"}147                    label={"Ram"}148                    options={149                        (filterAll && filterAll.laptop.rams) ||150                        LIST_RENDER_DEFAULT151                    }152                    rules={[{ required: true }]}153                />154                <SelectField155                    name={"rom_id"}156                    label={"Lưu trữ"}157                    options={158                        (filterAll && filterAll.laptop.roms) ||159                        LIST_RENDER_DEFAULT160                    }161                    rules={[{ required: true }]}162                />163                <SelectField164                    name={"gpu_id"}165                    label={"Card Äá» há»a"}166                    options={167                        (filterAll && filterAll.laptop.gpus) ||168                        LIST_RENDER_DEFAULT169                    }170                    rules={[{ required: true }]}171                />172                <SelectField173                    name={"screen_id"}174                    label={"KÃch thưá»t màn hình"}175                    options={176                        (filterAll && filterAll.laptop.screens) ||177                        LIST_RENDER_DEFAULT178                    }179                    rules={[{ required: true }]}180                />181                <SelectField182                    name={"port_id"}183                    label={"Kết ná»i chÃnh"}184                    options={185                        (filterAll && filterAll.laptop.ports) ||186                        LIST_RENDER_DEFAULT187                    }188                    rules={[{ required: true }]}189                />190                <SelectField191                    name={"battery_id"}192                    label={"PIN"}193                    options={194                        (filterAll && filterAll.laptop.batteries) ||195                        LIST_RENDER_DEFAULT196                    }197                    rules={[{ required: true }]}198                />199                <SelectField200                    name={"weight_id"}201                    label={"Trá»ng lượng"}202                    options={203                        (filterAll && filterAll.laptop.weights) ||204                        LIST_RENDER_DEFAULT205                    }206                    rules={[{ required: true }]}207                />208                <SelectField209                    name={"size_id"}210                    label={"KÃch thưá»c"}211                    options={212                        (filterAll && filterAll.laptop.sizes) ||213                        LIST_RENDER_DEFAULT214                    }215                    rules={[{ required: true }]}216                />217                <SelectField218                    name={"os_id"}219                    label={"Há» Äiá»u hành"}220                    options={221                        (filterAll && filterAll.laptop.os) ||222                        LIST_RENDER_DEFAULT223                    }224                    rules={[{ required: true }]}225                />226            </Col>227        )228    }229    const renderSpecDrive = () => {230        return (231            <Col span={12}>232                <SelectField233                    name={"drive_type_id"}234                    label={"Kiá»u á» cứng"}235                    options={236                        (filterAll && filterAll.drive.types) ||237                        LIST_RENDER_DEFAULT238                    }239                    onChange={value => {240                        dispatch(241                            setIsSSDForCreateDrive(242                                value % 2 === 0 ? true : false243                            )244                        )245                    }}246                    rules={[{ required: true }]}247                />248                <SelectField249                    name={"capacity_id"}250                    label={"Dung lượng"}251                    options={252                        (filterAll && filterAll.drive.capacities) ||253                        LIST_RENDER_DEFAULT254                    }255                    rules={[{ required: true }]}256                />257                <SelectField258                    name={"connect_id"}259                    label={"Kết ná»i"}260                    options={261                        (filterAll && filterAll.drive.connections) ||262                        LIST_RENDER_DEFAULT263                    }264                    rules={[{ required: true }]}265                />266                <SelectField267                    name={"dimension_id"}268                    label={"KÃch thưá»t"}269                    options={270                        (filterAll && filterAll.drive.dimensions) ||271                        LIST_RENDER_DEFAULT272                    }273                    rules={[{ required: true }]}274                />275                <SelectField276                    name={"read_id"}277                    label={"Tá»c Äá» Äá»c"}278                    options={279                        (filterAll && filterAll.drive.reads) ||280                        LIST_RENDER_DEFAULT281                    }282                    rules={[{ required: true }]}283                />284                <SelectField285                    name={"write_id"}286                    label={"Tá»c Äá» ghi"}287                    options={288                        (filterAll && filterAll.drive.writes) ||289                        LIST_RENDER_DEFAULT290                    }291                    rules={[{ required: true }]}292                />293                <SelectField294                    name={"rotation_id"}295                    label={"Tá»c Äá» quay"}296                    options={297                        (filterAll && filterAll.drive.rotations) ||298                        LIST_RENDER_DEFAULT299                    }300                    rules={isSSDForCreateDrive ? [] : [{ required: true }]}301                    disabled={isSSDForCreateDrive}302                />303                <SelectField304                    name={"cache_id"}305                    label={"Bá» nhá»m Äá»m"}306                    options={307                        (filterAll && filterAll.drive.caches) ||308                        LIST_RENDER_DEFAULT309                    }310                    rules={isSSDForCreateDrive ? [] : [{ required: true }]}311                    disabled={isSSDForCreateDrive}312                />313            </Col>314        )315    }316    //------------------------HANDLE RENDER------------------------317    const handleRenderSpec = () => {318        switch (productTypeIdForCreate) {319            case 1:320                return renderSpecLaptop()321            case 2:322                return renderSpecDrive()323            default:324                return <p>Há» thá»ng Äang cáºp nháºt</p>325        }326    }327    const handleRenderBrand = () => {328        switch (productTypeIdForCreate) {329            case 1:330                return filterAll && filterAll.laptop.brands331            case 2:332                return filterAll && filterAll.drive.brands333            default:334                break335        }336    }337    return (338        <div>339            <BreadcrumbField list={["Admin", "Thêm má»i"]} />340            <h3 style={{ textAlign: "center", marginBottom: "30px" }}>341                {"Thêm má»i sản phẩm"}342            </h3>343            <Form344                // form={form}345                key={indexForm}346                {...layout}347                name="nest-messages"348                onFinish={onFinish}349                validateMessages={VALIDATE_MESSAGES}350                // onFieldsChange={(_, allFields) => {351                //     handleInputChange(allFields)352                // }}353            >354                <Row>355                    <Col span={12}>356                        <SelectField357                            name={"type_id"}358                            label={"Loại sản phẩm"}359                            options={360                                (filterAll && filterAll.type) ||361                                LIST_RENDER_DEFAULT362                            }363                            onChange={value => {364                                dispatch(setProductTypeIdForCreate(value))365                            }}366                            rules={[{ required: true }]}367                        />368                        <SelectField369                            name={"brand_id"}370                            label={"Hãng sản phẩm"}371                            options={handleRenderBrand() || LIST_RENDER_DEFAULT}372                            rules={[{ required: true }]}373                        />374                        <InputField375                            typeInput={TYPE_CUSTOM_FIELD.INPUT}376                            name={"name"}377                            label={"Tên sản phẩm"}378                            rules={[{ required: true }]}379                        />380                        <InputField381                            typeInput={TYPE_CUSTOM_FIELD.INPUT}382                            name={"img1"}383                            label={"Link Ảnh 1"}384                            prefix={<LinkOutlined />}385                            rules={[{ required: true }]}386                        />387                        <InputField388                            typeInput={TYPE_CUSTOM_FIELD.INPUT}389                            name={"img2"}390                            label={"Link Ảnh 2"}391                            prefix={<LinkOutlined />}392                            rules={[{ required: true }]}393                        />394                        <InputField395                            typeInput={TYPE_CUSTOM_FIELD.INPUT}396                            name={"img3"}397                            label={"Link Ảnh 3"}398                            prefix={<LinkOutlined />}399                            rules={[{ required: true }]}400                        />401                        <InputField402                            typeInput={TYPE_CUSTOM_FIELD.TEXTAREA}403                            name={"description"}404                            label={"Mô tả sản phẩm"}405                            rules={[{ required: true }]}406                        />407                        <InputField408                            typeInput={TYPE_CUSTOM_FIELD.INPUT}409                            name={"price"}410                            label={"Giá sản phẩm"}411                            suffix={"VNÄ"}412                            rules={[{ required: true }]}413                        />414                        <InputField415                            typeInput={TYPE_CUSTOM_FIELD.INPUT_NUMBER}416                            name={"guarantee"}417                            label={"Thá»i gian bảo hành (tháng)"}418                            rules={[419                                {420                                    required: true,421                                    type: "number",422                                    min: 0,423                                    max: 99424                                }425                            ]}426                        />427                    </Col>428                    {/* render col right */}429                    {handleRenderSpec()}430                    <Row431                        style={{432                            width: "100%",433                            display: "flex",434                            justifyContent: "center"435                        }}436                    >437                        <Space size={"small"}>438                            <Button439                                type="primary"440                                htmlType="submit"441                                icon={<SaveOutlined />}442                            >443                                Lưu444                            </Button>445                            <Button446                                text="Há»§y"447                                htmlType="cancel"448                                icon={<CloseOutlined />}449                                onClick={() => onCancel()}450                            >451                                Há»§y452                            </Button>453                        </Space>454                    </Row>455                </Row>456            </Form>457        </div>458    )459}...utils.unit.spec.ts
Source:utils.unit.spec.ts  
1import { getPrevCursor, getNextCursor } from "./utils";2const sectionIsExpanded = () => true;3const sectionIsNotExpanded = () => false;4const filterAll = () => true;5const filterEvenIds = (item: any) => item.id % 2 === 0;6const sections = [7  {8    id: 1,9    items: [10      {11        id: 1,12      },13      {14        id: 2,15      },16    ],17  },18  {19    id: 2,20    items: [21      {22        id: 3,23      },24      {25        id: 4,26      },27    ],28  },29];30describe("getNextCursor", () => {31  it("returns the first section selected when initial cursor is null and selecting sections allowed", () => {32    expect(33      getNextCursor(null, sections, sectionIsExpanded, true, filterAll),34    ).toStrictEqual({ sectionIndex: 0, itemIndex: null });35  });36  it("returns the first item of the first section selected when initial cursor is null and selecting sections is not allowed", () => {37    expect(38      getNextCursor(null, sections, sectionIsExpanded, false, filterAll),39    ).toStrictEqual({ sectionIndex: 0, itemIndex: 0 });40  });41  it("returns the first item of the first section selected when initial cursor is on the first section", () => {42    expect(43      getNextCursor(44        { sectionIndex: 0, itemIndex: null },45        sections,46        sectionIsExpanded,47        false,48        filterAll,49      ),50    ).toStrictEqual({ sectionIndex: 0, itemIndex: 0 });51  });52  it("returns the section section if first section is selected but not expanded", () => {53    expect(54      getNextCursor(55        { sectionIndex: 0, itemIndex: null },56        sections,57        sectionIsNotExpanded,58        true,59        filterAll,60      ),61    ).toStrictEqual({ sectionIndex: 1, itemIndex: null });62  });63  it("returns the second item when the first was selected", () => {64    expect(65      getNextCursor(66        { sectionIndex: 0, itemIndex: 0 },67        sections,68        sectionIsExpanded,69        false,70        filterAll,71      ),72    ).toStrictEqual({ sectionIndex: 0, itemIndex: 1 });73  });74  it("returns the second section when on the last item of the first section and selecting sections is allowed", () => {75    expect(76      getNextCursor(77        { sectionIndex: 0, itemIndex: 1 },78        sections,79        sectionIsExpanded,80        true,81        filterAll,82      ),83    ).toStrictEqual({ sectionIndex: 1, itemIndex: null });84  });85  it("returns the first item of the second section when on the last item of the first section and selecting sections is not allowed", () => {86    expect(87      getNextCursor(88        { sectionIndex: 0, itemIndex: 1 },89        sections,90        sectionIsExpanded,91        false,92        filterAll,93      ),94    ).toStrictEqual({ sectionIndex: 1, itemIndex: 0 });95  });96  it("returns the last item when on the last item", () => {97    expect(98      getNextCursor(99        { sectionIndex: 1, itemIndex: 1 },100        sections,101        sectionIsExpanded,102        false,103        filterAll,104      ),105    ).toStrictEqual({ sectionIndex: 1, itemIndex: 1 });106  });107  it("skips filtered out items", () => {108    expect(109      getNextCursor(110        { sectionIndex: 0, itemIndex: 1 },111        sections,112        sectionIsExpanded,113        false,114        filterEvenIds,115      ),116    ).toStrictEqual({ sectionIndex: 1, itemIndex: 1 });117  });118});119describe("getPrevCursor", () => {120  it("returns the first section when initial cursor is null and selecting sections allowed", () => {121    expect(122      getPrevCursor(null, sections, sectionIsExpanded, true, filterAll),123    ).toStrictEqual({ sectionIndex: 0, itemIndex: null });124  });125  it("returns the first section when on the first item and selecting sections allowed", () => {126    expect(127      getPrevCursor(128        { sectionIndex: 0, itemIndex: 0 },129        sections,130        sectionIsExpanded,131        true,132        filterAll,133      ),134    ).toStrictEqual({ sectionIndex: 0, itemIndex: null });135  });136  it("returns the first item when on the first item and selecting sections is not allowed", () => {137    expect(138      getPrevCursor(139        { sectionIndex: 0, itemIndex: 0 },140        sections,141        sectionIsExpanded,142        false,143        filterAll,144      ),145    ).toStrictEqual({ sectionIndex: 0, itemIndex: 0 });146  });147  it("returns the first item when on the second item", () => {148    expect(149      getPrevCursor(150        { sectionIndex: 0, itemIndex: 1 },151        sections,152        sectionIsExpanded,153        false,154        filterAll,155      ),156    ).toStrictEqual({ sectionIndex: 0, itemIndex: 0 });157  });158  it("returns first section when on the second and the first is collapsed", () => {159    expect(160      getPrevCursor(161        { sectionIndex: 1, itemIndex: null },162        sections,163        sectionIsNotExpanded,164        true,165        filterAll,166      ),167    ).toStrictEqual({ sectionIndex: 0, itemIndex: null });168  });169  it("returns the last item of the first section when on the second section and the first is expanded", () => {170    expect(171      getPrevCursor(172        { sectionIndex: 1, itemIndex: null },173        sections,174        sectionIsExpanded,175        true,176        filterAll,177      ),178    ).toStrictEqual({ sectionIndex: 0, itemIndex: 1 });179  });180  it("skips filtered out items", () => {181    expect(182      getPrevCursor(183        { sectionIndex: 1, itemIndex: 1 },184        sections,185        sectionIsExpanded,186        false,187        filterEvenIds,188      ),189    ).toStrictEqual({ sectionIndex: 0, itemIndex: 1 });190  });...filterButtons.test.js
Source:filterButtons.test.js  
1import userEvent from '@testing-library/user-event';2import React from 'react';3import App from '../App';4import renderWithRouterAndRedux from './helpers/renderWithRouterAndRedux';5describe('Teste de filtro de receita principal comidas', () => {6  it('Testando se todo os botôes de filtro estão presente na tela principal de comidas',7    async () => {8      const { history, findByTestId } = renderWithRouterAndRedux(<App />);9      history.push('/comidas');10      const filterAll = await findByTestId('All-category-filter');11      const filterBeef = await findByTestId('Beef-category-filter');12      expect(filterAll).toBeInTheDocument();13      expect(filterBeef).toBeInTheDocument();14      userEvent.click(filterAll);15      userEvent.click(filterBeef);16      expect(1 + 1).toBe(2);17    });18});19describe('Teste de filtro de receita principal bebidas', () => {20  it('Testando se todo os botôes de filtro estão presente na tela principal de bebidas',21    async () => {22      const { history, findByTestId } = renderWithRouterAndRedux(<App />);23      history.push('/bebidas');24      const filterAll = await findByTestId('All-category-filter');25      const filterOrdinary = await findByTestId('Ordinary Drink-category-filter');26      expect(filterAll).toBeInTheDocument();27      expect(filterOrdinary).toBeInTheDocument();28      userEvent.click(filterAll);29      userEvent.click(filterOrdinary);30      expect(1 + 1).toBe(2);31    });...Using AI Code Generation
1const stf = require('devicefarmer-stf-client');2const client = stf.connect();3client.getDevices().then(devices => {4    devices.filterAll().then(devices => {5        console.log(devices);6    });7});8[ { serial: 'emulator-5554',9    display: { id: 0, width: 1080, height: 1920 },Using AI Code Generation
1var stf = require('devicefarmer-stf-client');2var devices = client.getDevices();3devices.filterAll().then(function(allDevices) {4  console.log(allDevices);5});6var stf = require('devicefarmer-stf-client');7var devices = client.getDevices();8devices.filterAvailable().then(function(availableDevices) {9  console.log(availableDevices);10});11var stf = require('devicefarmer-stf-client');12var devices = client.getDevices();13devices.filterBusy().then(function(busyDevices) {14  console.log(busyDevices);15});16var stf = require('devicefarmer-stf-client');17var devices = client.getDevices();18devices.filterBy({owner: 'Using AI Code Generation
1var stf = require('devicefarmer-stf-client');2client.getDevices().then(function(devices){3    devices.filterAll();4});5var stf = require('devicefarmer-stf-client');6client.getDevices().then(function(devices){7    devices.filterAll();8});9var stf = require('devicefarmer-stf-client');10client.getDevices().then(function(devices){11    devices.filterAll();12});13var stf = require('devicefarmer-stf-client');14client.getDevices().then(function(devices){15    devices.filterAll();16});17var stf = require('devicefarmer-stf-client');18client.getDevices().then(function(devices){19    devices.filterAll();20});21var stf = require('devicefarmer-stf-client');22client.getDevices().then(function(devices){23    devices.filterAll();24});25var stf = require('devicefarmer-stf-client');26client.getDevices().then(function(devices){27    devices.filterAll();28});29var stf = require('devicefarmer-stf-client');30client.getDevices().then(function(devices){31    devices.filterAll();32});Using AI Code Generation
1var stf = require('devicefarmer-stf');2var devices = client.getDevices();3devices.filterAll({ready:true,owner:null}).then(function(devices){4    console.log('Found ' + devices.length + ' devices');5});6var stf = require('devicefarmer-stf');7var devices = client.getDevices();8devices.filterAll({ready:true,owner:null}).then(function(devices){9    console.log('Found ' + devices.length + ' devices');10});11var stf = require('devicefarmer-stf');12var devices = client.getDevices();13devices.filterAll({ready:true,owner:null}).then(function(devices){14    console.log('Found ' + devices.length + ' devices');15});16var stf = require('devicefarmer-stf');17var devices = client.getDevices();18devices.filterAll({ready:true,owner:null}).then(function(devices){19    console.log('Found ' + devices.length + ' devices');20});21var stf = require('devicefarmer-stf');22var devices = client.getDevices();23devices.filterAll({ready:true,owner:null}).then(function(devices){24    console.log('Found ' + devices.length + ' devices');25});26var stf = require('devicefarmer-stf');27var devices = client.getDevices();28devices.filterAll({ready:true,owner:null}).then(function(devices){29    console.log('Found ' + devices.length + ' devices');30});31var stf = require('devicefarmer-stf');32var devices = client.getDevices();33devices.filterAll({ready:true,owner:null}).then(function(devices){34    console.log('Found ' + devices.length + ' devices');35});36var stf = require('devicefarmer-stf');37var devices = client.getDevices();38devices.filterAll({ready:true,owner:null}).thenUsing AI Code Generation
1var stf = require('devicefarmer-stf-client');2stfClient.filterAll('Samsung Galaxy S4', 'v4.4.2', 'wifi', 'free').then(function (devices) {3    console.log(devices);4});5[ { serial: '0123456789ABCDEF',6       timeout: 60000 },7     { id: 0,8    phone: { number: null },9     { type: 'wifi',10       roaming: false },11     { status: 2,12       technology: 'Li-ion' },13     { type: 'WIFI',Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
