代码之家  ›  专栏  ›  技术社区  ›  darKnight

jest-函数不调用其子异步函数

  •  0
  • darKnight  · 技术社区  · 7 年前

    Login handleLoginSubmit 提交表单时调用的方法。这个方法实际上是在我的 store 登录

    handleLoginSubmit = async (event) => {
        event.preventDefault();
        const result = await service.validateUser(this.username, this.password);
        if (result) {
            this.isAuthenticated = true;
            this.invalidLogin = false;
            history.push('/search');
        }
        else this.invalidLogin = true;
    }
    

    我已经编写了测试用例来检查 handleSubmit 提交表单时,以及验证是否正确:

    describe('Login should authenticate users corectly when', () => {
    
        it('correct credentials are submitted', async () => {
            const spySubmit = jest.spyOn(store, 'handleLoginSubmit');
            const spyValidate = jest.spyOn(service, 'validateUser');
            const wrapper = shallow(<Login store={store} />);
            expect(spySubmit).toHaveBeenCalledTimes(0);
            wrapper.find('form').simulate('submit');
            expect(spySubmit).toHaveBeenCalledTimes(1);
            expect(spyValidate).toBeCalledWith({ username: store.username, password: store.password });
        });
    });
    

    服务.js:

    export function validateUser(username, password) {
        return fetch(`https://abc.co/api?search=${username}`)
            .then(function (response) {
                return response.json();
            }).then(function (response) {
                if (response.results.length) {
                    if (response.results[0].key === password) {
                        return true;
                    }
                    else return false;
                }
                else return false;
            });
    }
    

    service.validateUser 即使没有,也不会被调用 登录

    1 回复  |  直到 7 年前
        1
  •  1
  •   Rudy Huynh    7 年前

    问题是你 expect

    expect(store.handleLoginSubmit).toHaveBeenCalledTimes(0)
    

    期待

    .mockRestore() 以下内容:

    store.handleLoginSubmit.mockRestore()
    

    store.handleLoginSubmit 商店.手工提交

    test('.handleLoginSubmit() called when form is submitted', () => {
      jest.spyOn(store, 'handleLoginSubmit').mockImplementation(() => {})
      const wrapper = shallow(<Login store={store} />);
      wrapper.find('form').simulate('submit');
      expect(store.handleLoginSubmit).toBeCalled()
      store.handleLoginSubmit.mockRestore()
    })
    
    test('.handleLoginSubmit()', async () => {
      jest.spyOn(service, 'validateUser')
        .mockImplementation(() => Promise.resolve(true))
      await store.handleLoginSubmit({preventDefault: () => {}})
      expect(service.validateUser).toBeCalled()
      service.validateUser.mockRestore()
    })