[英]Jest mocking implementation of a method accepting callback of third party
我正在使用 Nest + Cognito 對應用程序上的用戶進行身份驗證,我的身份驗證服務中有一個方法,我正在嘗試測試/模擬,它是:
async cognitoRegister(userPool: CognitoUserPool, {
name,
password,
email
}: AuthRegisterInput): Promise < ISignUpResult > {
return new Promise((resolve, reject) => {
return userPool.signUp(
name,
password,
[new CognitoUserAttribute({
Name: 'email',
Value: email
})],
null,
(err, result) => {
if (!result) {
reject(err);
} else {
resolve(result);
}
},
);
});
}
這里的注冊function 是來自第三方 CognitoUserPool 的方法,我設法使用 package.Z466DEEC76ECDF5FCA6D38571F6324D5Z 中的模塊名稱映射器對其進行了模擬,這里是:
function CognitoUserPool(data) {
const { UserPoolId, ClientId } = data;
this.userPoolId = UserPoolId;
this.clientId = ClientId;
this.getCurrentUser = jest.fn().mockReturnValue("cognitouserpool");
// This method
this.signUp = jest.fn().mockReturnValue(true);
}
module.exports = CognitoUserPool;
並且是實施:
module.exports = {
CognitoUserPool: jest.fn().mockImplementation(require("./CognitoUserPool")),
};
由於 signUp 方法接受一個回調,它負責給我一個結果/拒絕值,我應該以某種方式模擬它,否則 Jest 給我一個超時錯誤,因為實現返回一個 Promise,它停留在待處理的 state 中。
基本上我正在嘗試模擬這種 function:
const foo = (arg1, cb) => {
...do something...
}
const bar = (arg1, arg2...) => {
return new Promise((resolve, reject) => {
return foo(arg1, (err, result) => {
if (!result) {
reject(err)
} else {
resolve(result)
}
})
})
}
這是我在測試中嘗試做的事情:
it("should register a cognito user", async () => {
const mockedCongitoUserPool = new CognitoUserPool({
UserPoolId: authConfig.userPoolId,
ClientId: authConfig.clientId,
});
const result = await service.cognitoRegister(mockedCongitoUserPool, {
...mockedUser,
});
console.log(result);
});
我還有一個 git 可能會有所幫助:
感謝這里的任何幫助<3,要求任何進一步的解釋我真的需要一些幫助。
要獲得 static 分辨率,您的模擬模塊應聲明如下所示的實現,而不僅僅是返回值:
this.signUp = jest.fn().mockImplementation((name, pwd, attlist, something, cb) => {
process.nextTick(cb(null, 'signedup!'))
});
這里process.nextTick
只是模擬異步,但如果你不在乎,你也可以調用cb(null, 'some result')
。
如果您想動態控制回調解析,您可以根據您的場景覆蓋默認的模擬實現:
let cup: CognitoUserPool;
beforeAll(() => { // or maybe beforeEach, depends on what the mock keeps/does
cup = new CognitoUserPool({ userPoolId: 'fakeUserPoolId', ClientId: 'fakeClientId' });
});
it('should resolve', async () => {
const expected = { any: 'thing' };
cup.signUp.mockImplementation((a, b, c, d, cb) => cb(null, expected));
await expect(service.cognitoRegister(cup, mockedUser)).resolves.toBe(expected);
});
it('should fail', async () => {
const expected = new Error('boom!');
cup.signUp.mockImplementation((a, b, c, d, cb) => cb(expected));
await expect(service.cognitoRegister(cup, mockedUser)).rejects.toThrow(expected);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.