我正在使用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
});当我console.log(result)我得到
{ data: { forgotPassword: true } }这种行为不是我想要的,因为在.mockReturnValue中,我抛出一个错误,因此期望result有一个错误对象
但是,在此测试之前,将运行另一个
it('should throw an error if wrong credentials were provided', async () => {
callMethod
.mockReturnValue(new Error('cannot login'))
.mockName('callMethod');它运行良好,会抛出错误。
我想问题是模拟测试结束后不会被重置。在我的jest.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() {
...更新
当我用.mockReturnValue代替.mockImplementation时,一切都如期而至:
callMethod.mockImplementation(() => {
throw new Error('User not found');
});但这并不能解释为什么在另一个测试中.mockReturnValue运行良好.
发布于 2018-06-02 11:57:56
用.mockReturnValue更改.mockImplementation
yourMockInstance.mockImplementation(() => {
throw new Error();
});如果你想断言
test('the fetch fails with an error', () => {
return expect(fetchData()).rejects.toMatch('error');
});如果这是你对.rejects www.jestjs.io/docs/en/asynchronous#resolves--rejects的承诺
发布于 2021-07-29 18:59:17
对于承诺,可以使用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()
})发布于 2020-04-02 16:14:43
角+ Jest:
import { throwError } from 'rxjs';
yourMockInstance.mockImplementation(() => {
return throwError(new Error('my error message'));
});https://stackoverflow.com/questions/49835264
复制相似问题