WMS_MAIN/test/app/service/systems/auth.user.loginWechatCode.test.js

104 lines
3.1 KiB
JavaScript

'use strict';
const assert = require('node:assert/strict');
const UserService = require('../../../../app/service/systems/auth/user');
function createServiceHarness() {
const cacheWrites = [];
const cacheStore = new Map();
const app = {
async setCacheAsync(cacheKey, data, expireSeconds = 300) {
cacheWrites.push({
cacheKey,
data,
expireSeconds,
});
if (data === null || data === undefined || expireSeconds <= 1) {
cacheStore.delete(cacheKey);
return;
}
cacheStore.set(cacheKey, data);
},
async getCacheAsync(cacheKey) {
return cacheStore.has(cacheKey) ? cacheStore.get(cacheKey) : null;
},
coreLogger: {
warn() {},
error() {},
},
};
const ctx = {
app,
};
const service = new UserService(ctx);
return {
app,
ctx,
service,
cacheWrites,
cacheStore,
};
}
describe('test/app/service/systems/auth.user.loginWechatCode.test.js', () => {
it('should generate client code and login code when client code is missing', async () => {
const { service, cacheWrites } = createServiceHarness();
const result = await service.getLoginWechatCode({});
assert.equal(result.success, true);
assert.equal(result.code, 200);
assert.match(String(result.data.client_code || ''), /^(?=.*[A-Z])(?=.*\d)[A-Z\d]{6}$/);
assert.match(String(result.data.code || ''), /^(?=.*[A-Z])(?=.*\d)[A-Z\d]{6}$/);
assert.equal(result.data.status, 'pending');
assert.ok(String(result.message || '').includes('客户端编码'));
const writesWithState = cacheWrites.filter(item => item && item.data && item.data.client_code === result.data.client_code);
assert.equal(writesWithState.length, 2);
for (const write of writesWithState) {
assert.equal(write.expireSeconds, 60);
}
});
it('should refresh login code after long poll when client code is provided', async () => {
const { service, cacheWrites } = createServiceHarness();
service.waitForLoginCodeRefresh = async () => {};
const first = await service.getLoginWechatCode({});
const firstCode = String(first.data.code || '');
const clientCode = String(first.data.client_code || '');
const second = await service.getLoginWechatCode({
clientCode,
});
assert.equal(second.success, true);
assert.equal(second.code, 200);
assert.equal(String(second.data.client_code || ''), clientCode);
assert.match(String(second.data.code || ''), /^(?=.*[A-Z])(?=.*\d)[A-Z\d]{6}$/);
assert.notEqual(String(second.data.code || ''), firstCode);
assert.ok(String(second.message || '').includes('长轮询结束'));
const invalidationWrite = cacheWrites.find(item => item && item.data === null && item.expireSeconds === 1);
assert.ok(invalidationWrite);
});
it('should fail when provided client code format is invalid', async () => {
const { service } = createServiceHarness();
const result = await service.getLoginWechatCode({
clientCode: 'abc',
});
assert.equal(result.success, false);
assert.equal(result.code, 0);
assert.match(String(result.message || ''), /客户端编码/);
});
});