[英]Jest mock for redis-sessions functions
我想模擬 redis-session function。
static async createSession(userData: string, userId: Uuid, ipAddress: string = 'NA'): Promise<string> {
try {
const rs = this.getRedisConnection();
return new Promise<string>((resolve, reject): void => {
rs.create(
{
app: Configs.rsSessionApp,
id: userId,
ip: ipAddress,
ttl: Configs.rsDefaultTtl,
d: {
data: userData,
},
},
(err: object, resp: { token: string }): void => {
if (resp !== undefined && resp.token.length > 0) {
return resolve(resp.token);
}
if (err != null) {
reject(err);
}
},
);
});
} catch (error) {
return Promise.reject(error.message);
}
}
我想讓這一行執行 (err: object, resp: { token: string }): void => {} How to implement or resolve this using jest unit test?。 另一個拋出錯誤的單元測試。
try...catch...
無法捕捉到異步代碼的異常,可以去掉。
您可以使用jest.spyOn(object, methodName)模擬RedisSession.getRedisConnection()
方法並返回一個模擬的 redis 連接。 然后,模擬rs.create()
方法的實現,你可以在你的測試用例中得到匿名回調 function。
最后,使用模擬的 arguments 手動調用匿名回調 function。
例如
index.ts
:
import RedisSessions from 'redis-sessions';
interface Uuid {}
export class RedisSession {
static async createSession(userData: string, userId: Uuid, ipAddress: string = 'NA'): Promise<string> {
const rs = this.getRedisConnection();
return new Promise<string>((resolve, reject): void => {
rs.create(
{
app: 'test',
id: userId,
ip: ipAddress,
ttl: 3600,
d: {
data: userData,
},
},
(err: object, resp: { token: string }): void => {
if (resp !== undefined && resp.token.length > 0) {
return resolve(resp.token);
}
if (err != null) {
reject(err);
}
}
);
});
}
static getRedisConnection() {
return new RedisSessions({ host: '127.0.0.1', port: '6379', namespace: 'rs' });
}
}
index.test.ts
:
import { RedisSession } from './';
describe('67220364', () => {
it('should create redis connection', async () => {
const mRs = {
create: jest.fn().mockImplementationOnce((option, callback) => {
callback(null, { token: '123' });
}),
};
const getRedisConnectionSpy = jest.spyOn(RedisSession, 'getRedisConnection').mockReturnValueOnce(mRs);
const actual = await RedisSession.createSession('teresa teng', '1');
expect(actual).toEqual('123');
expect(getRedisConnectionSpy).toBeCalledTimes(1);
expect(mRs.create).toBeCalledWith(
{
app: 'test',
id: '1',
ip: 'NA',
ttl: 3600,
d: {
data: 'teresa teng',
},
},
expect.any(Function)
);
});
});
單元測試結果:
PASS examples/67220364/index.test.ts (8.636 s)
67220364
✓ should create redis connection (5 ms)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 70 | 57.14 | 75 | 70 |
index.ts | 70 | 57.14 | 75 | 70 | 24-33
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 9.941 s
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.