Vue组件中的toHaveBeenCalled()开玩笑测试失败

时间:2018-11-29 13:58:09

标签: javascript unit-testing vue.js jestjs

在测试中使用“点击”触发器的函数调用无法正常工作。

  1. 我叫函数-它正在工作
  2. 我触发了点击,但测试失败。

    describe("Message.test.js", () => {
        let wrapper;
        const createWrapper = propsData => mount(Message, { propsData 
    
        describe("Events", () => {
            beforeEach(() => {
             wrapper = createWrapper({ message: "Cat" });
        }); 
    
        //Working
        it("calls handleClick", () => {
            const spy = jest.spyOn(wrapper.vm, 'handleClick');
            wrapper.vm.handleClick();
            expect(spy).toHaveBeenCalled();
        });
    
        //NOT WORKING. WHY?
    
        it("calls handleClick when click on message", () => {
            wrapper.vm.handleClick = jest.fn();
            //It is Ok
            expect(wrapper.contains('.message')).toBe(true);
            // @click="handleClick" on element
            wrapper.find('.message').trigger('click');
            expect(wrapper.vm.handleClick).toHaveBeenCalledTimes(1);
        })
    });
    

我在函数中添加了console.log。在测试过程中,我看到了调用了什么函数。

1 个答案:

答案 0 :(得分:1)

 it('calls handleClick when click on message', () => {
            const handleClick = jest.fn()
            wrapper.setMethods({ handleClick })
            const el = wrapper.find('.message').trigger('click')
            expect(handleClick).toBeCalled()
        })
// stub
        it('triggers a message-clicked event when a handleClick method is called', () => {
            const stub = jest.fn()
            wrapper.vm.$on('message-clicked', stub)
            wrapper.vm.handleClick()
            expect(stub).toBeCalledWith('Cat')
        })