簡體   English   中英

笑話 - 如何在笑話中模擬 class

[英]Jest - how to mock a class in jest

我一直在嘗試通過他們在文檔中提供的方法來開玩笑地模擬測試。 通過 mocking 整個 class 但我似乎無法讓它正常工作。

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 });

我想將 state 更新為字符串響應,但改為未定義。 所以看起來我有點 mocking 的東西,但只是不正確。

您可以按如下方式使用spyOn為您做 mocking。 我還建議您在完成后設置並拆除此間諜。

因此,這里有一段示例代碼可以滿足您的要求:

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');
  });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM