尝试学习如何编写测试,当我有承诺时我该如何编写?
Trying to learn how to write tests, how do I write when I have a promise?
我创建了一个连接到 API 和 returns 承诺的函数。
我想测试那个函数,所以在 Jest 中创建了一个模拟函数来处理它,但是我不确定我这样做是对的,而且我发现很难找到关于如何编写好的单元测试的好资源。
export const sbConnect = (userId) => {
return new Promise((resolve, reject) => {
const sb = new SendBird({appId: APP_ID});
sb.connect(userId, API_Token, (user, error) => {
if (error) {
reject(error);
} else {
resolve(user);
}
});
});
};
这是我要测试的功能。到目前为止,我已经创建了一个测试并进行了尝试..
import {sbConnect} from '../helpers/sendBirdSetupActions';
const SendBird = jest.fn();
describe('Connects to SendBird API', () => {
it('Creates a new SB instance', () => {
let userId = 'testUser';
let APP_ID = 'Testing_App_ID_001';
sbConnect(userId);
expect(SendBird).toBeCalled();
});
});
您可以使用 jest.mock(moduleName, factory, options) 手动模拟 sendbird
模块。
Mock SendBird
构造函数、实例及其方法。
例如
index.ts
:
import SendBird from 'sendbird';
const API_Token = 'test api token';
const APP_ID = 'test api id';
export const sbConnect = (userId) => {
return new Promise((resolve, reject) => {
const sb = new SendBird({ appId: APP_ID });
sb.connect(userId, API_Token, (user, error) => {
if (error) {
reject(error);
} else {
resolve(user);
}
});
});
};
index.test.ts
:
import { sbConnect } from './';
import SendBird from 'sendbird';
const mSendBirdInstance = {
connect: jest.fn(),
};
jest.mock('sendbird', () => {
return jest.fn(() => mSendBirdInstance);
});
describe('65220363', () => {
afterAll(() => {
jest.resetAllMocks();
});
it('should get user', async () => {
const mUser = { name: 'teresa teng' };
mSendBirdInstance.connect.mockImplementationOnce((userId, API_Token, callback) => {
callback(mUser, null);
});
const actual = await sbConnect('1');
expect(actual).toEqual(mUser);
expect(SendBird).toBeCalledWith({ appId: 'test api id' });
expect(mSendBirdInstance.connect).toBeCalledWith('1', 'test api token', expect.any(Function));
});
it('should handle error', async () => {
const mError = new Error('network');
mSendBirdInstance.connect.mockImplementationOnce((userId, API_Token, callback) => {
callback(null, mError);
});
await expect(sbConnect('1')).rejects.toThrow(mError);
expect(SendBird).toBeCalledWith({ appId: 'test api id' });
expect(mSendBirdInstance.connect).toBeCalledWith('1', 'test api token', expect.any(Function));
});
});
单元测试结果:
PASS src/Whosebug/65220363/index.test.ts (11.115s)
65220363
✓ should get user (6ms)
✓ should get user (3ms)
----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.ts | 100 | 100 | 100 | 100 | |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 12.736s
源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/Whosebug/65220363
我创建了一个连接到 API 和 returns 承诺的函数。 我想测试那个函数,所以在 Jest 中创建了一个模拟函数来处理它,但是我不确定我这样做是对的,而且我发现很难找到关于如何编写好的单元测试的好资源。
export const sbConnect = (userId) => {
return new Promise((resolve, reject) => {
const sb = new SendBird({appId: APP_ID});
sb.connect(userId, API_Token, (user, error) => {
if (error) {
reject(error);
} else {
resolve(user);
}
});
});
};
这是我要测试的功能。到目前为止,我已经创建了一个测试并进行了尝试..
import {sbConnect} from '../helpers/sendBirdSetupActions';
const SendBird = jest.fn();
describe('Connects to SendBird API', () => {
it('Creates a new SB instance', () => {
let userId = 'testUser';
let APP_ID = 'Testing_App_ID_001';
sbConnect(userId);
expect(SendBird).toBeCalled();
});
});
您可以使用 jest.mock(moduleName, factory, options) 手动模拟 sendbird
模块。
Mock SendBird
构造函数、实例及其方法。
例如
index.ts
:
import SendBird from 'sendbird';
const API_Token = 'test api token';
const APP_ID = 'test api id';
export const sbConnect = (userId) => {
return new Promise((resolve, reject) => {
const sb = new SendBird({ appId: APP_ID });
sb.connect(userId, API_Token, (user, error) => {
if (error) {
reject(error);
} else {
resolve(user);
}
});
});
};
index.test.ts
:
import { sbConnect } from './';
import SendBird from 'sendbird';
const mSendBirdInstance = {
connect: jest.fn(),
};
jest.mock('sendbird', () => {
return jest.fn(() => mSendBirdInstance);
});
describe('65220363', () => {
afterAll(() => {
jest.resetAllMocks();
});
it('should get user', async () => {
const mUser = { name: 'teresa teng' };
mSendBirdInstance.connect.mockImplementationOnce((userId, API_Token, callback) => {
callback(mUser, null);
});
const actual = await sbConnect('1');
expect(actual).toEqual(mUser);
expect(SendBird).toBeCalledWith({ appId: 'test api id' });
expect(mSendBirdInstance.connect).toBeCalledWith('1', 'test api token', expect.any(Function));
});
it('should handle error', async () => {
const mError = new Error('network');
mSendBirdInstance.connect.mockImplementationOnce((userId, API_Token, callback) => {
callback(null, mError);
});
await expect(sbConnect('1')).rejects.toThrow(mError);
expect(SendBird).toBeCalledWith({ appId: 'test api id' });
expect(mSendBirdInstance.connect).toBeCalledWith('1', 'test api token', expect.any(Function));
});
});
单元测试结果:
PASS src/Whosebug/65220363/index.test.ts (11.115s)
65220363
✓ should get user (6ms)
✓ should get user (3ms)
----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.ts | 100 | 100 | 100 | 100 | |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 12.736s
源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/Whosebug/65220363