Code Monkey home page Code Monkey logo

Comments (9)

eddyerburgh avatar eddyerburgh commented on May 18, 2024 3

There's now a setMethods method.

We should have a setComputed method too. I've created a new issue for that:

#55

from vue-test-utils.

eddyerburgh avatar eddyerburgh commented on May 18, 2024 1

@philefstat

We could recommend this pattern:

const clickHandlerStub = sinon.stub()

wrapper.stubMethod('clickHandler', clickHandlerStub)
...
expect(clickHandlerStub.called).to.equal(true)

Or this:

const clickHandlerStub = sinon.stub()

wrapper.stubMethods({
  clickHandler: clickHandlerStub
})

from vue-test-utils.

heygambo avatar heygambo commented on May 18, 2024 1

setMethods worked great.

like here:

const spy = jest.spyOn(wrapper.vm, 'handleChange')
wrapper.setMethods({ handleChange: spy })
wrapper.find('.some-input').trigger('change')
expect(spy).toHaveBeenCalled()

from vue-test-utils.

jackmellis avatar jackmellis commented on May 18, 2024

I previously had a hook that was called before the component was mounted, which exposed a deep copy of the component so you could manually stub it's methods (without affecting the original component). But i actually really like your approach, I think it's really simple.

A couple of thoughts:

  • would you want the option to restore a stubbed method at a later point?
  • could you stub a method without having to provide an alternate function {clickHandler:true}
  • what about computed properties? There have been times when a method relies on a computed property that is so complicated it's taken me far outside the purpose of my unit test just to get the right computed value!

from vue-test-utils.

philefstat avatar philefstat commented on May 18, 2024

I prefer setMethods as it is consistent with setData and setProps. However, I think there should also be a method to retrieve them as it could be confusing that you then have to use the vm to check if it has been called.

wrapper.stubMethod(clickHandler, sinon.stub())
...
expect(wrapper.vm.clickHandler.called).to.equal(true)

With the current way, at least the way you set and get is consistent.

wrapper.vm.clickHandler = sinon.stub() 
...
expect(wrapper.vm.clickHandler.called).to.equal(true)

from vue-test-utils.

eddyerburgh avatar eddyerburgh commented on May 18, 2024

@jackmellis

would you want the option to restore a stubbed method at a later point?

I don't think so, with stubMethod you could save the original before stubbing and then restore it later with the same method.

could you stub a method without having to provide an alternate function {clickHandler:true}

Yes I think that's a good idea

what about computed properties?

Yes I think that a setComputed method would be a good idea if setData does not work for a use case. Would you be able to provide example where setData doesn't work, so I can use it as a test case?

from vue-test-utils.

philefstat avatar philefstat commented on May 18, 2024

@eddyerburgh those both look great 👍

That pattern also allows some of the useful sinon methods to be called on the stub without reaching directly into the vm.

i.e.
clickhandlerStub.resetHistory()

stubMethods could be quite useful for larger components with multiple methods that need to be stubbed.

const methods = {
  foo: sinon.stub().returns(3),
  bar: sinon.stub(),
  baz: sinon.stub().throws("TypeError")
}

wrapper.stubMethods(methods)

...

expect(methods.foo).to.be.calledOnce
expect(methods.bar).to.be.calledTwice

from vue-test-utils.

chandreshSpringer avatar chandreshSpringer commented on May 18, 2024

Hi All,

  const spy = sinon.stub()
  wrapper.setMethods({ onClickCreate: spy })
  wrapper.find('#btn-create-proposal').trigger('click')
  expect(spy.called).toBe(true)

this is not working.
In Actual the method defined in component being mounted is being called.
Thanks for help in advance

from vue-test-utils.

god-of-js avatar god-of-js commented on May 18, 2024

Hey guys,
Hey guys, I have this file picker component that I am trying to test. The component receives the file through the takeFile method.

<script lang="ts">
import { defineComponent, ref } from '@nuxtjs/composition-api'
import AppButtonCard from '~/components/Button/AppButtonCard.vue'
export default defineComponent({
  components: {
    AppButtonCard
  },
  setup (_props, { emit }) {
    const isDraging = ref(false)
    const openFilePicker = () => {
      (document.querySelector('#file-upload') as any).click()
    }
    const handleSelectedFiles = (e: any) => {
      const file = takeFile(e)
      if (isValidFile(file)) {
        emit('getFile', file)
      } else {
        emit('invalidFile')
      }
    }
    const takeFile = (e: any) => {
      return e.dataTransfer ? [...e.dataTransfer.files][0] : e.target.files[0]
    }
    const isValidFile = (file: File) => {
      try {
        const acceptedSuffixTypes = ['pdf', 'epub', 'txt', 'docx', 'rtf']
        const fileName = file.name
        const dot = fileName.lastIndexOf('.')
        const suffix = fileName.substr(dot + 1)
        if (acceptedSuffixTypes.includes(suffix)) {
          return true
        } else {
          return false
        }
      } catch (_) {
        return false
      }
    }
    return {
      openFilePicker,
      handleSelectedFiles,
      isDraging
    }
  }
})
</script>

I am trying to mock the takeFile method so that when it is called, it uses the mocked file. I am making use of sinon. But it seems the fileis not getting into the component.

import { mount } from '@vue/test-utils'
import sinon from 'sinon'
import FileUpload from './FileUpload.vue'
describe('~/components/Files/FileUpload.vue', () => {
  it('it emits an error when an invalid file is picked.', () => {
    const invalidFile = {
      name: 'image.png',
      size: 2887225,
      type: 'image/jpeg',
      lastModified: 1639671510625,
      lastModifiedDate: 'Thu Dec 16 2021 17:18:30 GMT+0100 (West Africa Standard Time)'
    }
    const takeFile = sinon.fake.returns(invalidFile)
    const wrapper = mount(FileUpload, {
      mocks: {
        takeFile
      }
    })

    const fileInput = wrapper.find('input[type="file"]')
    fileInput.trigger('change')

    expect(wrapper.emitted().invalidFile).toBeDefined()
  })
  it('it emits the file when the file is valid and has been processed.', () => {
    const validFile = {
      name: 'document.pdf',
      size: 2887225,
      type: 'application/pdf',
      lastModified: 1639671510625,
      lastModifiedDate: 'Thu Dec 16 2021 17:18:30 GMT+0100 (West Africa Standard Time)'
    }
    const takeFile = sinon.fake.returns(validFile)
    const wrapper = mount(FileUpload, {
      mocks: {
        takeFile
      }
    })
    const fileInput = wrapper.find('input[type="file"]')
    fileInput.trigger('change')

    expect(wrapper.emitted().getFile).toBe([[validFile]])
  })
})

Please, I urgently need help with this.
I have tried this and it's not working.
I think it's because I am using the composition API and I think this should work in the options API
I have also tried accessing the takeFile method directly like this

wrapper.vm.takeFile = sinon.fake.returns(validFile)

from vue-test-utils.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.