簡體   English   中英

模擬依賴的構造函數 Jest

[英]Mock a dependency's constructor Jest

我是 Jest 的新手。 我設法模擬了我自己的東西,但似乎被困在模擬模塊中。 特別是構造函數。

用法.js

const AWS = require("aws-sdk")
cw = new AWS.CloudWatch({apiVersion: "2010-08-01"})
...
function myMetrics(params) { 
  cw.putMetricData(params, function(err, data){})
}

我想在測試中做這樣的事情。

const AWS = jest.mock("aws-sdk")
class FakeMetrics {
  constructor() {}
  putMetricData(foo,callback) {
    callback(null, "yay!")
  }
}

AWS.CloudWatch = jest.fn( (props) => new FakeMetrics())

但是,當我在usage.js使用它時,cw 是一個mockConstructor而不是FakeMetrics

我意識到我的方法可能“不太習慣”,所以我會很樂意提供任何指示。

這是一個最小的例子https://github.com/ollyjshaw/jest_constructor_so

npm install -g jest

jest

以上答案有效。 但是,在使用jest一段時間后,我只會使用mockImplementation功能,這對於模擬構造函數很有用。

下面的代碼可以是一個例子:

import * as AWS from 'aws-sdk';

jest.mock('aws-sdk', ()=> {
    return {
        CloudWatch : jest.fn().mockImplementation(() => { return {} })
    }
});

test('AWS.CloudWatch is called', () => {
    new AWS.CloudWatch();
    expect(AWS.CloudWatch).toHaveBeenCalledTimes(1);
});

請注意,在示例中, new CloudWatch()僅返回一個空對象。

問題是如何模擬模塊。 正如參考文獻所述,

在需要時使用自動模擬版本模擬模塊。 <...> 返回用於鏈接的 jest 對象。

AWS不是模塊對象但jest對象,並指定AWS.CloudFormation會影響什么。

此外,它CloudWatch在一個地方, CloudFormation在另一個。

測試框架不需要重新發明模擬函數,它們已經存在。 它應該是這樣的:

const AWS = require("aws-sdk");
const fakePutMetricData = jest.fn()
const FakeCloudWatch = jest.fn(() => ({
    putMetricData: fakePutMetricData
}));                        
AWS.CloudWatch = FakeCloudWatch;

並斷言:

expect(fakePutMetricData).toHaveBeenCalledTimes(1);

根據文檔mockImplementation也可用於模擬類構造函數:

// SomeClass.js
module.exports = class SomeClass {
  method(a, b) {}
};

// OtherModule.test.js
jest.mock('./SomeClass'); // this happens automatically with automocking
const SomeClass = require('./SomeClass');
const mockMethod= jest.fn();
SomeClass.mockImplementation(() => {
  return {
    method: mockMethod,
  };
});

const some = new SomeClass();
some.method('a', 'b');
console.log('Calls to method: ', mockMethod.mock.calls);

如果您的類構造函數有參數,您可以將jest.fn()作為參數傳遞(例如const some = new SomeClass(jest.fn(), jest.fn());

暫無
暫無

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

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