gpt4 book ai didi

javascript - 使用 jest.unmock 测试 Promise

转载 作者:行者123 更新时间:2023-11-28 05:00:59 26 4
gpt4 key购买 nike

我正在使用 Auth0 来管理我的 React 应用程序的身份验证。这是我要测试的功能:

login(username: string, password: string) {
return new Promise((resolve, reject) => {
this.auth0.client.login({
realm: 'Username-Password-Authentication',
username,
password,
}, (err, authResult) => {
if (err) {
reject(err);
}
if (authResult && authResult.idToken && authResult.accessToken) {
resolve(authResult.idToken);
}
});
});
}

auth0 通过以下方式实例化:

constructor(clientID: string, domain: string, redirectUri: string) {
// Configure auth0
this.auth0 = new auth0.WebAuth({
clientID,
domain,
responseType: 'token id_token',
redirectUri,
});
}

我有以下两个测试:

  • 我想看看是否可以实例化 AuthService 类。
  • 我想看看是否可以使用用户名/密码组合登录

这是我编写的测试文件:

jest.unmock('../AuthService');

import AuthService from '../AuthService';

describe('Auth0 Library', () => {
test('Should be able to instantiate', () => {
const auth0 = new AuthService('clientID', 'domain');
expect(auth0).toEqual(expect.anything());
});
});

describe('Auth0 Login', () => {
test('Fetch token for existing user', () => {
const auth0 = new AuthService('clientID', 'domain');
auth0.login('email', 'pw')
.then((idToken) => {
console.log('idToken ', idToken);
expect(auth0).toEqual(expect.anything());
});
});
});

第一个测试按预期运行。然而,第二个测试永远不会起作用。返回的 promise 似乎从未得到解决,而且我从未看到console.log。

有人可以向我解释一下我做错了什么吗?在编写 Jest 测试方面我相当陌生。

最佳答案

这是一起使用 Promise 和错误优先回调的单元测试解决方案。

文件夹结构:

.
├── AuthService.spec.ts
├── AuthService.ts
└── auth0
├── WebAuth.ts
└── index.ts

1 directory, 4 files

例如

AuthService.ts:

import * as auth0 from './auth0';

export class AuthService {
private auth0: any;
constructor(clientID: string, domain: string, redirectUri: string) {
this.auth0 = new auth0.WebAuth({
clientID,
domain,
responseType: 'token id_token',
redirectUri
});
}

public login(username: string, password: string) {
return new Promise((resolve, reject) => {
this.auth0.client.login(
{
realm: 'Username-Password-Authentication',
username,
password
},
(err, authResult) => {
if (err) {
reject(err);
}
if (authResult && authResult.idToken && authResult.accessToken) {
resolve(authResult.idToken);
}
}
);
});
}
}

auth0/WebAuth.ts:

export class WebAuth {
public client = {
login(options, callback) {
callback(null, {});
}
};
constructor(...args: any) {}
}

auth0/index.ts:

export * from './WebAuth';

AuthService.spec.ts:

import { AuthService } from './AuthService';

const authService = new AuthService('clientid', 'domain', 'redirectUri');

describe('AuthService', () => {
describe('#login', () => {
afterEach(() => {
jest.restoreAllMocks();
});
it('should login successfully and return id token', async done => {
let loginCallback;
jest.spyOn(authService['auth0']['client'], 'login').mockImplementation((options, callback) => {
loginCallback = callback;
done();
});
const actualValue = authService.login('username', 'password');
const mAuthResult = { idToken: '123', accessToken: '321' };
loginCallback(null, mAuthResult);
await expect(actualValue).resolves.toBe('123');
});

it('should login failed', async done => {
let loginCallback;
jest.spyOn(authService['auth0']['client'], 'login').mockImplementation((options, callback) => {
loginCallback = callback;
done();
});
const actualValue = authService.login('username', 'password');
const mError = new Error('network error');
loginCallback(mError, null);
await expect(actualValue).rejects.toThrowError(mError);
});
});
});

AuthService.ts 覆盖率为 100% 的单元测试结果:

 PASS  src/stackoverflow/42137891/AuthService.spec.ts
AuthService
#login
✓ should login successfully and return id token (5ms)
✓ should login failed (2ms)

---------------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
---------------------|----------|----------|----------|----------|-------------------|
All files | 95 | 100 | 87.5 | 94.12 | |
42137891-todo | 100 | 100 | 100 | 100 | |
AuthService.ts | 100 | 100 | 100 | 100 | |
42137891-todo/auth0 | 85.71 | 100 | 66.67 | 83.33 | |
WebAuth.ts | 83.33 | 100 | 66.67 | 80 | 4 |
index.ts | 100 | 100 | 100 | 100 | |
---------------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 3.728s

源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/42137891

关于javascript - 使用 jest.unmock 测试 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42137891/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com