开玩笑-如何在开玩笑中模拟课程

时间:2019-11-22 09:04:01

标签: reactjs unit-testing jestjs

我一直在尝试通过他们文档中的方法来嘲笑测试。通过嘲笑整个班级,但我似乎无法使其正常工作。

https://jestjs.io/docs/en/es6-class-mocks

jest.mock('../../../../../src/SubscriptionOrder');
    SubscriptionOrder.prototype.createChargebeeSubscription = jest.fn(() => 'response');

const test = new SubscriptionOrder(
  'subscription',
  [{}],
  'errorMethods',
  'customerMethods',
);
test.createChargebeeSubscription();

我希望它可以模拟createChargebeeSubscription方法并返回字符串响应,但它似乎返回未定义的

然后这也是我试图对其进行测试的一段代码。

      const subscriptionOrder = new SubscriptionOrder(
    'subscription',
    subscriptionRequest,
    errorMethods,
    customerMethods,
  );
  const response = await subscriptionOrder.createChargebeeSubscription(token);
  this.setState({ successfulSubmit: response });

我想将状态更新为字符串响应,但改为未定义。所以看来我有点在嘲笑某些东西,但只是做得不好。

1 个答案:

答案 0 :(得分:0)

您可以按以下方式使用spyOn为您进行模拟。我还建议您在完成后设置并拆除该间谍。

所以这是一段示例代码,可以完成您想要的操作:

describe('createChargebeeSubscription() method behaviour', () => {
  let createChargebeeSubscriptionSpy;
  let testResponse;

  beforeAll(() => {
   // Lets create an instance of your class first
   const subscriptionOrder = new SubscriptionOrder(
     'subscription',
     subscriptionRequest,
     errorMethods,
     customerMethods
   );

   // Now use a spy to mock the return value from your function
   createChargebeeSubscriptionSpy = jest.spyOn(subscriptionOrder, 'createChargebeeSubscription').mockImplementation(() => {
     return 'response';
   });

   // Finally invoke the method being tested
   testResponse = subscriptionOrder.createChargebeeSubscription();
  });

  afterAll(() => {
    // Restore the functionality (ie. disable the spy) of your method
    createChargebeeSubscriptionSpy.mockRestore();
  });

  it('verifies that the expected response was returned', () => {
    expect(testResponse).toBe('response');
  });
});