我正在使用Jest测试我的GraphQL api。
我为每个查询/变异使用单独的测试套装
我有两个测试(每个测试都在一套单独的测试套件中),其中我模拟了一个用于突变的函数(即Meteor的callMethod
)。
it('should throw error if email not found', async () => {
callMethod
.mockReturnValue(new Error('User not found [403]'))
.mockName('callMethod');
const query = FORGOT_PASSWORD_MUTATION;
const params = { email: 'user@example.com' };
const result = await simulateQuery({ query, params });
console.log(result);
// test logic
expect(callMethod).toBeCalledWith({}, 'forgotPassword', {
email: 'user@example.com',
});
// test resolvers
});
当我控制台时。日志(结果)
我得到
{ data: { forgotPassword: true } }
这种行为不是我想要的,因为在. mockRecnValue
中,我抛出了一个错误,因此期望结果
有一个错误对象
然而,在这个测试之前,还进行了另一个测试
it('should throw an error if wrong credentials were provided', async () => {
callMethod
.mockReturnValue(new Error('cannot login'))
.mockName('callMethod');
它工作正常,抛出错误
我想问题是mock在测试完成后不会被重置。在我的玩笑中。conf.js
我有clearMocks:true
每个测试套件都在一个单独的文件中,我在进行以下测试之前模拟函数:
import simulateQuery from '../../../helpers/simulate-query';
import callMethod from '../../../../imports/api/users/functions/auth/helpers/call-accounts-method';
import LOGIN_WITH_PASSWORD_MUTATION from './mutations/login-with-password';
jest.mock(
'../../../../imports/api/users/functions/auth/helpers/call-accounts-method'
);
describe('loginWithPassword mutation', function() {
...
使现代化
当我替换时。使用
模拟返回值。模拟实施
一切按预期进行:
callMethod.mockImplementation(() => {
throw new Error('User not found');
});
但这并不能解释为什么在另一个测试中。
更改。使用
模拟返回值。模拟实现
:
yourMockInstance.mockImplementation(() => {
throw new Error();
});
如果这是一个promise,你也可以拒绝www.jestjs.io/docs/en/asynchronous#resolves--rejects
角笑话:
import { throwError } from 'rxjs';
yourMockInstance.mockImplementation(() => {
return throwError(new Error('my error message'));
});
对于promise,可以使用https://jestjs.io/docs/mock-function-api#mockfnmockrejectedvaluevalue
test('async test', async () => {
const asyncMock = jest.fn().mockRejectedValue(new Error('Async error'));
await asyncMock(); // throws "Async error"
});
对于测试是否引发了错误,可以使用https://eloquentcode.com/expect-a-function-to-throw-an-exception-in-jest
const func = () => {
throw new Error('my error')
}
it('should throw an error', () => {
expect(func).toThrow()
})