存根运行承诺的函数

问题描述 投票:1回答:2

我一直在尝试为新的反应应用程序编写注册页面的单元测试

但是我对Sinon存根/间谍的概念很新,并且在拦截函数调用和强制解决方面遇到了问题。

这是我的初步测试:

test('Success notification is displayed if all information is valid', () => {
  wrapper.setState({ username: 'test', password: 'Test1234!@', confirmPassword: 'Test1234!@' });
  const stub = sinon.stub(Register.prototype, 'signUp').resolves('Test');
  wrapper.find('#submitRegistration').simulate('click');
});

onClick运行此事件处理程序:(简化)

public onSubmitHandler(e: React.FormEvent) {
  // Perform password match check
  if (password === confirmPassword) {
      this.signUp(this.state.username, password);
    } else {
      // Set success state
    }
  } else {
    // Set error state
  }
}

注册:

public signUp(username: string, password: string) {
  // Perform Cognito Signup
  return Auth.signUp({
    password,
    username,
  })
    .then(() => {
      // Set success State
    })
    .catch((err) => {
      // Set error state
    });
}

如何拦截对signUp的调用并将其强制执行解析路径,目前由于我没有配置我的AWS Amplify Auth模块,因此每次都会捕获“No userPool”

reactjs typescript jestjs sinon aws-amplify
2个回答
0
投票

Jest提供了许多模拟依赖关系的方法,主要有两种风格:

  1. Manual Mocks - 这些让你可以更详细地控制模拟。
  2. Mock functions - 如果您需要一个简单的模拟来解决常见问题,例如翻译,这些非常有帮助。

对于您的情况,您还需要处理Promises,因此,您需要遵循testing async behaviour的建议。

对于你的情况,我假设:

  1. Auth是一个名为“auth-module”的模块
  2. 你只需要设置一次模拟,并有1个测试数据,这些数据解析成功,1个失败。

// telling jest to mock the entire module
    jest.mock("auth-module", () => ({
      // telling jest which method to mock
      signUp: ({ password, username }) =>
        new Promise((resolve, reject) => {
          // setting the test expectations / test data
          process.nextTick(
            () =>
              username === "SuccessUser"
                ? resolve(userName)
                : reject({
                    error: "failure message"
                  })
          );
        })
    }));

注意:即使它不会运行,也要添加代码段,因为格式化似乎会被代码块破坏。


0
投票

通过dubes的回答,我设法得到以下内容:

const signUpSpy = jest.spyOn(Auth, 'signUp').mockImplementation((user, password) => {
  return new Promise((res, rej) => {
    res();
  });
});

而不是直接监视我编写的函数并调用将其移动到Modules函数并从那里解决了承诺!

© www.soinside.com 2019 - 2024. All rights reserved.